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