Automation of LV2 plugin properties.
[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/types.h"
35
36 #include "i18n.h"
37
38 using namespace ARDOUR;
39 using namespace PBD;
40 using namespace std;
41
42 MidiPlaylist::MidiPlaylist (Session& session, const XMLNode& node, bool hidden)
43         : Playlist (session, node, DataType::MIDI, hidden)
44         , _note_mode(Sustained)
45 {
46 #ifndef NDEBUG
47         const XMLProperty* prop = node.property("type");
48         assert(prop && DataType(prop->value()) == DataType::MIDI);
49 #endif
50
51         in_set_state++;
52         if (set_state (node, Stateful::loading_state_version)) {
53                 throw failed_constructor ();
54         }
55         in_set_state--;
56
57         relayer ();
58 }
59
60 MidiPlaylist::MidiPlaylist (Session& session, string name, bool hidden)
61         : Playlist (session, name, DataType::MIDI, hidden)
62         , _note_mode(Sustained)
63 {
64 }
65
66 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, string name, bool hidden)
67         : Playlist (other, name, hidden)
68         , _note_mode(other->_note_mode)
69 {
70 }
71
72 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, framepos_t start, framecnt_t dur, string name, bool hidden)
73         : Playlist (other, start, dur, name, hidden)
74         , _note_mode(other->_note_mode)
75 {
76         /* this constructor does NOT notify others (session) */
77 }
78
79 MidiPlaylist::~MidiPlaylist ()
80 {
81 }
82
83 template<typename Time>
84 struct EventsSortByTimeAndType {
85     bool operator() (Evoral::Event<Time>* a, Evoral::Event<Time>* b) {
86             if (a->time() == b->time()) {
87                     if (parameter_is_midi ((AutomationType)a->event_type()) &&
88                         parameter_is_midi ((AutomationType)b->event_type())) {
89                             /* negate return value since we must return whether
90                              * or not a should sort before b, not b before a
91                              */
92                             return !MidiBuffer::second_simultaneous_midi_byte_is_first (a->buffer()[0], b->buffer()[0]);
93                     }
94             }
95             return a->time() < b->time();
96     }
97 };
98
99 /** Returns the number of frames in time duration read (eg could be large when 0 events are read) */
100 framecnt_t
101 MidiPlaylist::read (Evoral::EventSink<framepos_t>& dst, framepos_t start, framecnt_t dur, unsigned chan_n)
102 {
103         /* this function is never called from a realtime thread, so
104            its OK to block (for short intervals).
105         */
106
107         Playlist::RegionReadLock rl (this);
108
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 Evoral::OverlapStart:
130                 case Evoral::OverlapInternal:
131                 case Evoral::OverlapExternal:
132                         regs.push_back (*i);
133                         break;
134
135                 case Evoral::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                                         _note_trackers.insert (make_pair (mr.get(), tracker));
258                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
259                                 }
260                         }
261                 }
262
263                 if (!evlist.empty()) {
264
265                         /* sort the event list */
266                         EventsSortByTimeAndType<framepos_t> cmp;
267                         evlist.sort (cmp);
268
269 #ifndef NDEBUG
270                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Final we now have %1 events\n",  evlist.size()));
271                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
272                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
273                         }
274 #endif
275                         /* write into dst */
276                         for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
277                                 Evoral::Event<framepos_t>* ev (*e);
278                                 dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
279                                 delete ev;
280                         }
281
282                 }
283         }
284
285         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "-------------------------------------------------------------\n");
286         return dur;
287 }
288
289 void
290 MidiPlaylist::clear_note_trackers ()
291 {
292         Playlist::RegionWriteLock rl (this, false);
293
294         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
295                 delete n->second;
296         }
297         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 clears all note trackers\n", name()));
298         _note_trackers.clear ();
299 }
300
301 void
302 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
303 {
304         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
305         NoteTrackers::iterator t = _note_trackers.find (region.get());
306
307         /* GACK! THREAD SAFETY! */
308
309         if (t != _note_trackers.end()) {
310                 delete t->second;
311                 _note_trackers.erase (t);
312         }
313 }
314
315 int
316 MidiPlaylist::set_state (const XMLNode& node, int version)
317 {
318         in_set_state++;
319         freeze ();
320
321         if (Playlist::set_state (node, version)) {
322                 return -1;
323         }
324
325         thaw();
326         in_set_state--;
327
328         return 0;
329 }
330
331 void
332 MidiPlaylist::dump () const
333 {
334         boost::shared_ptr<Region> r;
335
336         cerr << "Playlist \"" << _name << "\" " << endl
337         << regions.size() << " regions "
338         << endl;
339
340         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
341                 r = *i;
342                 cerr << "  " << r->name() << " @ " << r << " ["
343                 << r->start() << "+" << r->length()
344                 << "] at "
345                 << r->position()
346                 << " on layer "
347                 << r->layer ()
348                 << endl;
349         }
350 }
351
352 bool
353 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
354 {
355         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
356
357         if (!r) {
358                 return false;
359         }
360
361         bool changed = false;
362
363         {
364                 RegionWriteLock rlock (this);
365                 RegionList::iterator i;
366                 RegionList::iterator tmp;
367
368                 for (i = regions.begin(); i != regions.end(); ) {
369
370                         tmp = i;
371                         ++tmp;
372
373                         if ((*i) == region) {
374                                 regions.erase (i);
375                                 changed = true;
376                         }
377
378                         i = tmp;
379                 }
380         }
381
382
383         if (changed) {
384                 /* overload this, it normally means "removed", not destroyed */
385                 notify_region_removed (region);
386         }
387
388         return changed;
389 }
390
391 set<Evoral::Parameter>
392 MidiPlaylist::contained_automation()
393 {
394         /* this function is never called from a realtime thread, so
395            its OK to block (for short intervals).
396         */
397
398         Playlist::RegionReadLock rl (this);
399         set<Evoral::Parameter> ret;
400
401         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
402                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
403
404                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
405                                 c != mr->model()->controls().end(); ++c) {
406                         ret.insert(c->first);
407                 }
408         }
409
410         return ret;
411 }
412
413
414 bool
415 MidiPlaylist::region_changed (const PBD::PropertyChange& what_changed, boost::shared_ptr<Region> region)
416 {
417         if (in_flush || in_set_state) {
418                 return false;
419         }
420
421         PBD::PropertyChange our_interests;
422         our_interests.add (Properties::midi_data);
423
424         bool parent_wants_notify = Playlist::region_changed (what_changed, region);
425
426         if (parent_wants_notify || what_changed.contains (our_interests)) {
427                 notify_contents_changed ();
428         }
429
430         return true;
431 }
432