4c200f60b541d88595816087a8e6e670421eabdf
[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                     Evoral::Range<framepos_t>*     loop_range,
114                     unsigned                       chan_n,
115                     MidiChannelFilter*             filter)
116 {
117         typedef pair<MidiStateTracker*,framepos_t> TrackerInfo;
118
119         Playlist::RegionReadLock rl (this);
120
121         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
122                      string_compose ("---- MidiPlaylist::read %1 .. %2 (%3 trackers) ----\n",
123                                      start, start + dur, _note_trackers.size()));
124
125         /* First, emit any queued edit fixup events at start. */
126         for (NoteTrackers::iterator t = _note_trackers.begin(); t != _note_trackers.end(); ++t) {
127                 t->second->fixer.emit(dst, _read_end, t->second->tracker);
128         }
129
130         /* Find relevant regions that overlap [start..end] */
131         const framepos_t                         end = start + dur - 1;
132         std::vector< boost::shared_ptr<Region> > regs;
133         std::vector< boost::shared_ptr<Region> > ended;
134         for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
135                 switch ((*i)->coverage (start, end)) {
136                 case Evoral::OverlapStart:
137                 case Evoral::OverlapInternal:
138                         regs.push_back (*i);
139                         break;
140
141                 case Evoral::OverlapExternal:
142                         /* this region is entirely contained in the read range */
143                         regs.push_back (*i);
144                         ended.push_back (*i);
145                         break;
146
147                 case Evoral::OverlapEnd:
148                         /* this region ends within the read range */
149                         regs.push_back (*i);
150                         ended.push_back (*i);
151                         break;
152
153                 default:
154                         /* we don't care */
155                         break;
156                 }
157         }
158
159         /* If we are reading from a single region, we can read directly into dst.  Otherwise,
160            we read into a temporarily list, sort it, then write that to dst. */
161         const bool direct_read = regs.size() == 1 &&
162                 (ended.empty() || (ended.size() == 1 && ended.front() == regs.front()));
163
164         Evoral::EventList<framepos_t>  evlist;
165         Evoral::EventSink<framepos_t>& tgt = direct_read ? dst : evlist;
166
167         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
168                      string_compose ("\t%1 regions to read, direct: %2\n", regs.size(), direct_read));
169
170         for (vector<boost::shared_ptr<Region> >::iterator i = regs.begin(); i != regs.end(); ++i) {
171                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*i);
172                 if (!mr) {
173                         continue;
174                 }
175
176                 /* Get the existing note tracker for this region, or create a new one. */
177                 NoteTrackers::iterator           t           = _note_trackers.find (mr.get());
178                 bool                             new_tracker = false;
179                 boost::shared_ptr<RegionTracker> tracker;
180                 if (t == _note_trackers.end()) {
181                         tracker     = boost::shared_ptr<RegionTracker>(new RegionTracker);
182                         new_tracker = true;
183                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
184                                      string_compose ("\tPre-read %1 (%2 .. %3): new tracker\n",
185                                                      mr->name(), mr->position(), mr->last_frame()));
186                 } else {
187                         tracker = t->second;
188                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
189                                      string_compose ("\tPre-read %1 (%2 .. %3): %4 active notes\n",
190                                                      mr->name(), mr->position(), mr->last_frame(), tracker->tracker.on()));
191                 }
192
193                 /* Read from region into target. */
194                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("read from %1 at %2 for %3 LR %4 .. %5\n",
195                                                                     mr->name(), start, dur, 
196                                                                     (loop_range ? loop_range->from : -1),
197                                                                     (loop_range ? loop_range->to : -1)));
198                 mr->read_at (tgt, start, dur, loop_range, tracker->cursor, chan_n, _note_mode, &tracker->tracker, filter);
199                 DEBUG_TRACE (DEBUG::MidiPlaylistIO,
200                              string_compose ("\tPost-read: %1 active notes\n", tracker->tracker.on()));
201
202                 if (find (ended.begin(), ended.end(), *i) != ended.end()) {
203                         /* Region ended within the read range, so resolve any active notes
204                            (either stuck notes in the data, or notes that end after the end
205                            of the region). */
206                         DEBUG_TRACE (DEBUG::MidiPlaylistIO,
207                                      string_compose ("\t%1 ended, resolve notes and delete (%2) tracker\n",
208                                                      mr->name(), ((new_tracker) ? "new" : "old")));
209
210                         tracker->tracker.resolve_notes (tgt, loop_range ? loop_range->squish ((*i)->last_frame()) : (*i)->last_frame());
211                         tracker->cursor.invalidate (false);
212                         if (!new_tracker) {
213                                 _note_trackers.erase (t);
214                         }
215
216                 } else {
217
218                         if (new_tracker) {
219                                 _note_trackers.insert (make_pair (mr.get(), tracker));
220                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
221                         }
222                 }
223         }
224
225         if (!direct_read && !evlist.empty()) {
226                 /* We've read from multiple regions, sort the event list by time. */
227                 EventsSortByTimeAndType<framepos_t> cmp;
228                 evlist.sort (cmp);
229
230                 /* Copy ordered events from event list to dst. */
231                 for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
232                         Evoral::Event<framepos_t>* ev (*e);
233                         dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
234                         delete ev;
235                 }
236         }
237
238         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "---- End MidiPlaylist::read ----\n");
239         _read_end = start + dur;
240         return dur;
241 }
242
243 void
244 MidiPlaylist::region_edited(boost::shared_ptr<Region>         region,
245                             const MidiModel::NoteDiffCommand* cmd)
246 {
247         typedef MidiModel::NoteDiffCommand Command;
248
249         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
250         if (!mr || !_session.transport_rolling()) {
251                 return;
252         }
253
254         /* Take write lock to prevent concurrency with read(). */
255         Playlist::RegionWriteLock lock(this);
256
257         NoteTrackers::iterator t = _note_trackers.find(mr.get());
258         if (t == _note_trackers.end()) {
259                 return; /* Region is not currently active, nothing to do. */
260         }
261
262         /* Queue any necessary edit compensation events. */
263         t->second->fixer.prepare(
264                 _session.tempo_map(), cmd, mr->position() - mr->start(),
265                 _read_end, t->second->cursor.active_notes);
266 }
267
268 void
269 MidiPlaylist::reset_note_trackers ()
270 {
271         Playlist::RegionWriteLock rl (this, false);
272
273         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 reset all note trackers\n", name()));
274         _note_trackers.clear ();
275 }
276
277 void
278 MidiPlaylist::resolve_note_trackers (Evoral::EventSink<framepos_t>& dst, framepos_t time)
279 {
280         Playlist::RegionWriteLock rl (this, false);
281
282         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
283                 n->second->tracker.resolve_notes(dst, time);
284         }
285         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 resolve all note trackers\n", name()));
286         _note_trackers.clear ();
287 }
288
289 void
290 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
291 {
292         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
293         _note_trackers.erase(region.get());
294 }
295
296 void
297 MidiPlaylist::region_going_away (boost::weak_ptr<Region> region)
298 {
299         boost::shared_ptr<Region> r = region.lock();
300         if (r) {
301                 remove_dependents(r);
302         }
303 }
304
305 int
306 MidiPlaylist::set_state (const XMLNode& node, int version)
307 {
308         in_set_state++;
309         freeze ();
310
311         if (Playlist::set_state (node, version)) {
312                 return -1;
313         }
314
315         thaw();
316         in_set_state--;
317
318         return 0;
319 }
320
321 void
322 MidiPlaylist::dump () const
323 {
324         boost::shared_ptr<Region> r;
325
326         cerr << "Playlist \"" << _name << "\" " << endl
327         << regions.size() << " regions "
328         << endl;
329
330         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
331                 r = *i;
332                 cerr << "  " << r->name() << " @ " << r << " ["
333                 << r->start() << "+" << r->length()
334                 << "] at "
335                 << r->position()
336                 << " on layer "
337                 << r->layer ()
338                 << endl;
339         }
340 }
341
342 bool
343 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
344 {
345         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
346
347         if (!r) {
348                 return false;
349         }
350
351         bool changed = false;
352
353         {
354                 RegionWriteLock rlock (this);
355                 RegionList::iterator i;
356                 RegionList::iterator tmp;
357
358                 for (i = regions.begin(); i != regions.end(); ) {
359
360                         tmp = i;
361                         ++tmp;
362
363                         if ((*i) == region) {
364                                 regions.erase (i);
365                                 changed = true;
366                         }
367
368                         i = tmp;
369                 }
370
371                 NoteTrackers::iterator t = _note_trackers.find(region.get());
372                 if (t != _note_trackers.end()) {
373                         _note_trackers.erase(t);
374                 }
375         }
376
377         if (changed) {
378                 /* overload this, it normally means "removed", not destroyed */
379                 notify_region_removed (region);
380         }
381
382         return changed;
383 }
384
385 set<Evoral::Parameter>
386 MidiPlaylist::contained_automation()
387 {
388         /* this function is never called from a realtime thread, so
389            its OK to block (for short intervals).
390         */
391
392         Playlist::RegionReadLock rl (this);
393         set<Evoral::Parameter> ret;
394
395         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
396                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
397
398                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
399                                 c != mr->model()->controls().end(); ++c) {
400                         if (c->second->list()->size() > 0) {
401                                 ret.insert(c->first);
402                         }
403                 }
404         }
405
406         return ret;
407 }