Move EventRingBuffer to libardour.
[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::clear_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 clears all note trackers\n", name()));
299         _note_trackers.clear ();
300 }
301
302 void
303 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
304 {
305         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
306         NoteTrackers::iterator t = _note_trackers.find (region.get());
307
308         /* GACK! THREAD SAFETY! */
309
310         if (t != _note_trackers.end()) {
311                 delete t->second;
312                 _note_trackers.erase (t);
313         }
314 }
315
316 int
317 MidiPlaylist::set_state (const XMLNode& node, int version)
318 {
319         in_set_state++;
320         freeze ();
321
322         if (Playlist::set_state (node, version)) {
323                 return -1;
324         }
325
326         thaw();
327         in_set_state--;
328
329         return 0;
330 }
331
332 void
333 MidiPlaylist::dump () const
334 {
335         boost::shared_ptr<Region> r;
336
337         cerr << "Playlist \"" << _name << "\" " << endl
338         << regions.size() << " regions "
339         << endl;
340
341         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
342                 r = *i;
343                 cerr << "  " << r->name() << " @ " << r << " ["
344                 << r->start() << "+" << r->length()
345                 << "] at "
346                 << r->position()
347                 << " on layer "
348                 << r->layer ()
349                 << endl;
350         }
351 }
352
353 bool
354 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
355 {
356         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
357
358         if (!r) {
359                 return false;
360         }
361
362         bool changed = false;
363
364         {
365                 RegionWriteLock rlock (this);
366                 RegionList::iterator i;
367                 RegionList::iterator tmp;
368
369                 for (i = regions.begin(); i != regions.end(); ) {
370
371                         tmp = i;
372                         ++tmp;
373
374                         if ((*i) == region) {
375                                 regions.erase (i);
376                                 changed = true;
377                         }
378
379                         i = tmp;
380                 }
381         }
382
383
384         if (changed) {
385                 /* overload this, it normally means "removed", not destroyed */
386                 notify_region_removed (region);
387         }
388
389         return changed;
390 }
391
392 set<Evoral::Parameter>
393 MidiPlaylist::contained_automation()
394 {
395         /* this function is never called from a realtime thread, so
396            its OK to block (for short intervals).
397         */
398
399         Playlist::RegionReadLock rl (this);
400         set<Evoral::Parameter> ret;
401
402         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
403                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
404
405                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
406                                 c != mr->model()->controls().end(); ++c) {
407                         ret.insert(c->first);
408                 }
409         }
410
411         return ret;
412 }
413
414
415 bool
416 MidiPlaylist::region_changed (const PBD::PropertyChange& what_changed, boost::shared_ptr<Region> region)
417 {
418         if (in_flush || in_set_state) {
419                 return false;
420         }
421
422         PBD::PropertyChange our_interests;
423         our_interests.add (Properties::midi_data);
424
425         bool parent_wants_notify = Playlist::region_changed (what_changed, region);
426
427         if (parent_wants_notify || what_changed.contains (our_interests)) {
428                 notify_contents_changed ();
429         }
430
431         return true;
432 }
433