fix crash when copy'ing latent plugins
[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 <algorithm>
21 #include <cassert>
22 #include <cstdlib>
23 #include <iostream>
24 #include <utility>
25
26 #include "evoral/EventList.hpp"
27 #include "evoral/Control.hpp"
28
29 #include "ardour/beats_frames_converter.h"
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_source.h"
35 #include "ardour/midi_state_tracker.h"
36 #include "ardour/session.h"
37 #include "ardour/types.h"
38
39 #include "pbd/i18n.h"
40
41 using namespace ARDOUR;
42 using namespace PBD;
43 using namespace std;
44
45 MidiPlaylist::MidiPlaylist (Session& session, const XMLNode& node, bool hidden)
46         : Playlist (session, node, DataType::MIDI, hidden)
47         , _note_mode(Sustained)
48         , _read_end(0)
49 {
50 #ifndef NDEBUG
51         XMLProperty const * 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         relayer ();
62 }
63
64 MidiPlaylist::MidiPlaylist (Session& session, string name, bool hidden)
65         : Playlist (session, name, DataType::MIDI, hidden)
66         , _note_mode(Sustained)
67         , _read_end(0)
68 {
69 }
70
71 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, string name, bool hidden)
72         : Playlist (other, name, hidden)
73         , _note_mode(other->_note_mode)
74         , _read_end(0)
75 {
76 }
77
78 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other,
79                             framepos_t                            start,
80                             framecnt_t                            dur,
81                             string                                name,
82                             bool                                  hidden)
83         : Playlist (other, start, dur, name, hidden)
84         , _note_mode(other->_note_mode)
85         , _read_end(0)
86 {
87 }
88
89 MidiPlaylist::~MidiPlaylist ()
90 {
91 }
92
93 template<typename Time>
94 struct EventsSortByTimeAndType {
95     bool operator() (Evoral::Event<Time>* a, Evoral::Event<Time>* b) {
96             if (a->time() == b->time()) {
97                     if (parameter_is_midi ((AutomationType)a->event_type()) &&
98                         parameter_is_midi ((AutomationType)b->event_type())) {
99                             /* negate return value since we must return whether
100                              * or not a should sort before b, not b before a
101                              */
102                             return !MidiBuffer::second_simultaneous_midi_byte_is_first (a->buffer()[0], b->buffer()[0]);
103                     }
104             }
105             return a->time() < b->time();
106     }
107 };
108
109 framecnt_t
110 MidiPlaylist::read (Evoral::EventSink<framepos_t>& dst,
111                     framepos_t                     start,
112                     framecnt_t                     dur,
113                     unsigned                       chan_n,
114                     MidiChannelFilter*             filter)
115 {
116         typedef pair<MidiStateTracker*,framepos_t> TrackerInfo;
117
118         Playlist::RegionReadLock rl (this);
119
120         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
121                      string_compose ("---- MidiPlaylist::read %1 .. %2 (%3 trackers) ----\n",
122                                      start, start + dur, _note_trackers.size()));
123
124         /* First, emit any queued edit fixup events at start. */
125         for (NoteTrackers::iterator t = _note_trackers.begin(); t != _note_trackers.end(); ++t) {
126                 t->second->fixer.emit(dst, _read_end, t->second->tracker);
127         }
128
129         /* Find relevant regions that overlap [start..end] */
130         const framepos_t                         end = start + dur - 1;
131         std::vector< boost::shared_ptr<Region> > regs;
132         std::vector< boost::shared_ptr<Region> > ended;
133         for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
134                 switch ((*i)->coverage (start, end)) {
135                 case Evoral::OverlapStart:
136                 case Evoral::OverlapInternal:
137                         regs.push_back (*i);
138                         break;
139
140                 case Evoral::OverlapExternal:
141                         /* this region is entirely contained in the read range */
142                         regs.push_back (*i);
143                         ended.push_back (*i);
144                         break;
145
146                 case Evoral::OverlapEnd:
147                         /* this region ends within the read range */
148                         regs.push_back (*i);
149                         ended.push_back (*i);
150                         break;
151
152                 default:
153                         /* we don't care */
154                         break;
155                 }
156         }
157
158         /* If we are reading from a single region, we can read directly into dst.  Otherwise,
159            we read into a temporarily list, sort it, then write that to dst. */
160         const bool direct_read = regs.size() == 1 &&
161                 (ended.empty() || (ended.size() == 1 && ended.front() == regs.front()));
162
163         Evoral::EventList<framepos_t>  evlist;
164         Evoral::EventSink<framepos_t>& tgt = direct_read ? dst : evlist;
165
166         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
167                      string_compose ("\t%1 regions to read, direct: %2\n", regs.size(), direct_read));
168
169         for (vector<boost::shared_ptr<Region> >::iterator i = regs.begin(); i != regs.end(); ++i) {
170                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*i);
171                 if (!mr) {
172                         continue;
173                 }
174
175                 /* Get the existing note tracker for this region, or create a new one. */
176                 NoteTrackers::iterator           t           = _note_trackers.find (mr.get());
177                 bool                             new_tracker = false;
178                 boost::shared_ptr<RegionTracker> tracker;
179                 if (t == _note_trackers.end()) {
180                         tracker     = boost::shared_ptr<RegionTracker>(new RegionTracker);
181                         new_tracker = true;
182                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
183                                      string_compose ("\tPre-read %1 (%2 .. %3): new tracker\n",
184                                                      mr->name(), mr->position(), mr->last_frame()));
185                 } else {
186                         tracker = t->second;
187                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
188                                      string_compose ("\tPre-read %1 (%2 .. %3): %4 active notes\n",
189                                                      mr->name(), mr->position(), mr->last_frame(), tracker->tracker.on()));
190                 }
191
192                 /* Read from region into target. */
193                 mr->read_at (tgt, start, dur, chan_n, _note_mode, &tracker->tracker, filter);
194                 DEBUG_TRACE (DEBUG::MidiPlaylistIO,
195                              string_compose ("\tPost-read: %1 active notes\n", tracker->tracker.on()));
196
197                 if (find (ended.begin(), ended.end(), *i) != ended.end()) {
198                         /* Region ended within the read range, so resolve any active notes
199                            (either stuck notes in the data, or notes that end after the end
200                            of the region). */
201                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
202                                      string_compose ("\t%1 ended, resolve notes and delete (%2) tracker\n",
203                                                      mr->name(), ((new_tracker) ? "new" : "old")));
204
205                         tracker->tracker.resolve_notes (tgt, (*i)->last_frame());
206                         if (!new_tracker) {
207                                 _note_trackers.erase (t);
208                         }
209
210                 } else {
211
212                         if (new_tracker) {
213                                 _note_trackers.insert (make_pair (mr.get(), tracker));
214                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
215                         }
216                 }
217         }
218
219         if (!direct_read && !evlist.empty()) {
220                 /* We've read from multiple regions, sort the event list by time. */
221                 EventsSortByTimeAndType<framepos_t> cmp;
222                 evlist.sort (cmp);
223
224                 /* Copy ordered events from event list to dst. */
225                 for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
226                         Evoral::Event<framepos_t>* ev (*e);
227                         dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
228                         delete ev;
229                 }
230         }
231
232         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "---- End MidiPlaylist::read ----\n");
233         _read_end = start + dur;
234         return dur;
235 }
236
237 void
238 MidiPlaylist::region_edited(boost::shared_ptr<Region>         region,
239                             const MidiModel::NoteDiffCommand* cmd)
240 {
241         typedef MidiModel::NoteDiffCommand Command;
242
243         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
244         if (!mr || !_session.transport_rolling()) {
245                 return;
246         }
247
248         /* Take write lock to prevent concurrency with read(). */
249         Playlist::RegionWriteLock lock(this);
250
251         NoteTrackers::iterator t = _note_trackers.find(mr.get());
252         if (t == _note_trackers.end()) {
253                 return; /* Region is not currently active, nothing to do. */
254         }
255
256         /* Queue any necessary edit compensation events. */
257         t->second->fixer.prepare(
258                 _session.tempo_map(), cmd, mr->position() - mr->start(),
259                 _read_end, mr->midi_source()->model()->active_notes());
260 }
261
262 void
263 MidiPlaylist::reset_note_trackers ()
264 {
265         Playlist::RegionWriteLock rl (this, false);
266
267         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 reset all note trackers\n", name()));
268         _note_trackers.clear ();
269 }
270
271 void
272 MidiPlaylist::resolve_note_trackers (Evoral::EventSink<framepos_t>& dst, framepos_t time)
273 {
274         Playlist::RegionWriteLock rl (this, false);
275
276         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
277                 n->second->tracker.resolve_notes(dst, time);
278         }
279         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 resolve all note trackers\n", name()));
280         _note_trackers.clear ();
281 }
282
283 void
284 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
285 {
286         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
287         _note_trackers.erase(region.get());
288 }
289
290 int
291 MidiPlaylist::set_state (const XMLNode& node, int version)
292 {
293         in_set_state++;
294         freeze ();
295
296         if (Playlist::set_state (node, version)) {
297                 return -1;
298         }
299
300         thaw();
301         in_set_state--;
302
303         return 0;
304 }
305
306 void
307 MidiPlaylist::dump () const
308 {
309         boost::shared_ptr<Region> r;
310
311         cerr << "Playlist \"" << _name << "\" " << endl
312         << regions.size() << " regions "
313         << endl;
314
315         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
316                 r = *i;
317                 cerr << "  " << r->name() << " @ " << r << " ["
318                 << r->start() << "+" << r->length()
319                 << "] at "
320                 << r->position()
321                 << " on layer "
322                 << r->layer ()
323                 << endl;
324         }
325 }
326
327 bool
328 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
329 {
330         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
331
332         if (!r) {
333                 return false;
334         }
335
336         bool changed = false;
337
338         {
339                 RegionWriteLock rlock (this);
340                 RegionList::iterator i;
341                 RegionList::iterator tmp;
342
343                 for (i = regions.begin(); i != regions.end(); ) {
344
345                         tmp = i;
346                         ++tmp;
347
348                         if ((*i) == region) {
349                                 regions.erase (i);
350                                 changed = true;
351                         }
352
353                         i = tmp;
354                 }
355         }
356
357
358         if (changed) {
359                 /* overload this, it normally means "removed", not destroyed */
360                 notify_region_removed (region);
361         }
362
363         return changed;
364 }
365
366 set<Evoral::Parameter>
367 MidiPlaylist::contained_automation()
368 {
369         /* this function is never called from a realtime thread, so
370            its OK to block (for short intervals).
371         */
372
373         Playlist::RegionReadLock rl (this);
374         set<Evoral::Parameter> ret;
375
376         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
377                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
378
379                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
380                                 c != mr->model()->controls().end(); ++c) {
381                         if (c->second->list()->size() > 0) {
382                                 ret.insert(c->first);
383                         }
384                 }
385         }
386
387         return ret;
388 }