Set up layering_index immediately on an explicit layer, so that undo
[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
25 #include <stdlib.h>
26
27 #include "pbd/error.h"
28
29 #include "evoral/EventList.hpp"
30
31 #include "ardour/configuration.h"
32 #include "ardour/debug.h"
33 #include "ardour/midi_model.h"
34 #include "ardour/midi_playlist.h"
35 #include "ardour/midi_region.h"
36 #include "ardour/midi_ring_buffer.h"
37 #include "ardour/session.h"
38 #include "ardour/types.h"
39
40 #include "i18n.h"
41
42 using namespace ARDOUR;
43 using namespace PBD;
44 using namespace std;
45
46 MidiPlaylist::MidiPlaylist (Session& session, const XMLNode& node, bool hidden)
47         : Playlist (session, node, DataType::MIDI, hidden)
48         , _note_mode(Sustained)
49 {
50 #ifndef NDEBUG
51         const XMLProperty* 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 {
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 {
74 }
75
76 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, framepos_t start, framecnt_t dur, string name, bool hidden)
77         : Playlist (other, start, dur, name, hidden)
78         , _note_mode(other->_note_mode)
79 {
80         /* this constructor does NOT notify others (session) */
81 }
82
83 MidiPlaylist::~MidiPlaylist ()
84 {
85 }
86
87 template<typename Time>
88 struct EventsSortByTimeAndType {
89     bool operator() (Evoral::Event<Time>* a, Evoral::Event<Time>* b) {
90             if (a->time() == b->time()) {
91                     if (EventTypeMap::instance().type_is_midi (a->event_type()) && EventTypeMap::instance().type_is_midi (b->event_type())) {
92                             /* negate return value since we must return whether
93                              * or not a should sort before b, not b before a
94                              */
95                             return !MidiBuffer::second_simultaneous_midi_byte_is_first (a->buffer()[0], b->buffer()[0]);
96                     }
97             }
98             return a->time() < b->time();
99     }
100 };
101
102 /** Returns the number of frames in time duration read (eg could be large when 0 events are read) */
103 framecnt_t
104 MidiPlaylist::read (Evoral::EventSink<framepos_t>& dst, framepos_t start, framecnt_t dur, unsigned chan_n)
105 {
106         /* this function is never called from a realtime thread, so
107            its OK to block (for short intervals).
108         */
109
110         Glib::RecMutex::Lock rm (region_lock);
111         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("++++++ %1 .. %2  +++++++ %3 trackers +++++++++++++++++\n", 
112                                                             start, start + dur, _note_trackers.size()));
113
114         framepos_t end = start + dur - 1;
115
116         // relevent regions overlapping start <--> end
117         vector< boost::shared_ptr<Region> > regs;
118         vector< boost::shared_ptr<Region> > ended;
119         typedef pair<MidiStateTracker*,framepos_t> TrackerInfo;
120         vector<TrackerInfo> tracker_info;
121         NoteTrackers::iterator t;
122
123         for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
124
125                 /* in this call to coverage, the return value indicates the
126                  * overlap status of the read range (start...end) WRT to 
127                  * the region.
128                  */
129
130                 switch ((*i)->coverage (start, end)) {
131                 case OverlapStart:
132                 case OverlapInternal:
133                 case OverlapExternal:
134                         regs.push_back (*i);
135                         break;
136
137                 case OverlapEnd:
138                         /* this region ends within the read range */
139                         regs.push_back (*i);
140                         ended.push_back (*i);
141                         break;
142                 default:
143                         /* we don't care */
144                         break;
145                 }
146         }
147
148         if (regs.size() == 1 && 
149             (ended.empty() || (ended.size() == 1 && ended.front() == regs.front()))) {
150
151                 /* just a single region - read directly into dst */
152
153                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Single region (%1) read, ended during this read %2\n", regs.front()->name(),
154                                                                     ended.size()));
155
156                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(regs.front());
157
158                 if (mr) {
159
160                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
161                         MidiStateTracker* tracker;
162                         bool new_tracker = false;
163
164                         if (t == _note_trackers.end()) {
165                                 tracker = new MidiStateTracker;
166                                 new_tracker = true;
167                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
168                         } else {
169                                 tracker = t->second;
170                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
171                         }
172
173                         mr->read_at (dst, start, dur, chan_n, _note_mode, tracker);
174                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
175
176                         if (!ended.empty()) {
177                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
178                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
179                                 tracker->resolve_notes (dst, mr->last_frame());
180                                 delete tracker;
181                                 if (!new_tracker) {
182                                         _note_trackers.erase (t);
183                                 }
184                         } else {
185                                 if (new_tracker) {
186                                         pair<Region*,MidiStateTracker*> newpair;
187                                         newpair.first = mr.get();
188                                         newpair.second = tracker;
189                                         _note_trackers.insert (newpair);
190                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
191                                 }
192                         }
193                 }
194
195         } else {
196
197                 /* multiple regions and/or note resolution: sort by layer, read into a temporary non-monotonically
198                    sorted EventSink, sort and then insert into dst.
199                 */
200
201                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("%1 regions to read, plus %2 trackers\n", regs.size(), tracker_info.size()));
202
203                 Evoral::EventList<framepos_t> evlist;
204
205                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("for %1 .. %2 we have %3 to consider\n", start, start+dur-1, regs.size()));
206
207                 for (vector<boost::shared_ptr<Region> >::iterator i = regs.begin(); i != regs.end(); ++i) {
208
209                         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*i);
210
211                         if (!mr) {
212                                 continue;
213                         }
214
215                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
216                         MidiStateTracker* tracker;
217                         bool new_tracker = false;
218
219                         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()));
220
221                         if (t == _note_trackers.end()) {
222                                 tracker = new MidiStateTracker;
223                                 new_tracker = true;
224                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
225                         } else {
226                                 tracker = t->second;
227                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
228                         }
229
230
231                         mr->read_at (evlist, start, dur, chan_n, _note_mode, tracker);
232
233 #ifndef NDEBUG
234                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("After %1 (%2 .. %3) we now have %4\n", mr->name(), mr->position(), mr->last_frame(), evlist.size()));
235                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
236                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
237                         }
238                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
239 #endif
240                         if (find (ended.begin(), ended.end(), *i) != ended.end()) {
241
242                                 /* the region ended within the read range, so
243                                  * resolve any dangling notes (i.e. notes whose
244                                  * end is beyond the end of the region).
245                                  */
246                                 
247                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
248                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
249
250                                 tracker->resolve_notes (evlist, (*i)->last_frame());
251                                 delete tracker;
252                                 if (!new_tracker) {
253                                         _note_trackers.erase (t);
254                                 }
255
256                         } else {
257
258                                 if (new_tracker) {
259                                         pair<Region*,MidiStateTracker*> newpair;
260                                         newpair.first = mr.get();
261                                         newpair.second = tracker;
262                                         _note_trackers.insert (newpair).first;
263                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
264                                 }
265                         }
266                 }
267
268                 if (!evlist.empty()) {
269
270                         /* sort the event list */
271                         EventsSortByTimeAndType<framepos_t> cmp;
272                         evlist.sort (cmp);
273
274 #ifndef NDEBUG
275                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Final we now have %1 events\n",  evlist.size()));
276                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
277                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
278                         }
279 #endif
280                         /* write into dst */
281                         for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
282                                 Evoral::Event<framepos_t>* ev (*e);
283                                 dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
284                                 delete ev;
285                         }
286
287                 }
288         }
289
290         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "-------------------------------------------------------------\n");
291         return dur;
292 }
293
294 void
295 MidiPlaylist::clear_note_trackers ()
296 {
297         Glib::RecMutex::Lock rm (region_lock);
298         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
299                 delete n->second;
300         }
301         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 clears all note trackers\n", name()));
302         _note_trackers.clear ();
303 }
304
305 void
306 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
307 {
308         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
309         NoteTrackers::iterator t = _note_trackers.find (region.get());
310
311         /* GACK! THREAD SAFETY! */
312
313         if (t != _note_trackers.end()) {
314                 delete t->second;
315                 _note_trackers.erase (t);
316         }
317 }
318
319
320 void
321 MidiPlaylist::refresh_dependents (boost::shared_ptr<Region> /*r*/)
322 {
323         /* MIDI regions have no dependents (crossfades) */
324 }
325
326 void
327 MidiPlaylist::finalize_split_region (boost::shared_ptr<Region> /*original*/, boost::shared_ptr<Region> /*left*/, boost::shared_ptr<Region> /*right*/)
328 {
329         /* No MIDI crossfading (yet?), so nothing to do here */
330 }
331
332 void
333 MidiPlaylist::check_dependents (boost::shared_ptr<Region> /*r*/, bool /*norefresh*/)
334 {
335         /* MIDI regions have no dependents (crossfades) */
336 }
337
338
339 int
340 MidiPlaylist::set_state (const XMLNode& node, int version)
341 {
342         in_set_state++;
343         freeze ();
344
345         if (Playlist::set_state (node, version)) {
346                 return -1;
347         }
348
349         thaw();
350         in_set_state--;
351
352         return 0;
353 }
354
355 void
356 MidiPlaylist::dump () const
357 {
358         boost::shared_ptr<Region> r;
359
360         cerr << "Playlist \"" << _name << "\" " << endl
361         << regions.size() << " regions "
362         << endl;
363
364         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
365                 r = *i;
366                 cerr << "  " << r->name() << " @ " << r << " ["
367                 << r->start() << "+" << r->length()
368                 << "] at "
369                 << r->position()
370                 << " on layer "
371                 << r->layer ()
372                 << endl;
373         }
374 }
375
376 bool
377 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
378 {
379         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
380
381         if (!r) {
382                 return false;
383         }
384
385         bool changed = false;
386
387         {
388                 RegionLock rlock (this);
389                 RegionList::iterator i;
390                 RegionList::iterator tmp;
391
392                 for (i = regions.begin(); i != regions.end(); ) {
393
394                         tmp = i;
395                         ++tmp;
396
397                         if ((*i) == region) {
398                                 regions.erase (i);
399                                 changed = true;
400                         }
401
402                         i = tmp;
403                 }
404         }
405
406
407         if (changed) {
408                 /* overload this, it normally means "removed", not destroyed */
409                 notify_region_removed (region);
410         }
411
412         return changed;
413 }
414
415 set<Evoral::Parameter>
416 MidiPlaylist::contained_automation()
417 {
418         /* this function is never called from a realtime thread, so
419            its OK to block (for short intervals).
420         */
421
422         Glib::RecMutex::Lock rm (region_lock);
423
424         set<Evoral::Parameter> ret;
425
426         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
427                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
428
429                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
430                                 c != mr->model()->controls().end(); ++c) {
431                         ret.insert(c->first);
432                 }
433         }
434
435         return ret;
436 }
437
438
439 bool
440 MidiPlaylist::region_changed (const PBD::PropertyChange& what_changed, boost::shared_ptr<Region> region)
441 {
442         if (in_flush || in_set_state) {
443                 return false;
444         }
445
446         PBD::PropertyChange our_interests;
447         our_interests.add (Properties::midi_data);
448
449         bool parent_wants_notify = Playlist::region_changed (what_changed, region);
450
451         if (parent_wants_notify || what_changed.contains (our_interests)) {
452                 notify_contents_changed ();
453         }
454
455         return true;
456 }
457