Invalidate iterator whenever model changes.
[ardour.git] / libs / ardour / midi_source.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 <sys/stat.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <float.h>
24 #include <cerrno>
25 #include <ctime>
26 #include <cmath>
27 #include <iomanip>
28 #include <algorithm>
29
30 #include <glibmm/fileutils.h>
31 #include <glibmm/miscutils.h>
32
33 #include "pbd/xml++.h"
34 #include "pbd/pthread_utils.h"
35 #include "pbd/basename.h"
36
37 #include "evoral/Control.hpp"
38 #include "evoral/EventSink.hpp"
39
40 #include "ardour/debug.h"
41 #include "ardour/midi_model.h"
42 #include "ardour/midi_state_tracker.h"
43 #include "ardour/midi_source.h"
44 #include "ardour/file_source.h"
45 #include "ardour/session.h"
46 #include "ardour/session_directory.h"
47 #include "ardour/source_factory.h"
48
49 #include "i18n.h"
50
51 namespace ARDOUR { template <typename T> class MidiRingBuffer; }
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56
57 PBD::Signal1<void,MidiSource*> MidiSource::MidiSourceCreated;
58
59 MidiSource::MidiSource (Session& s, string name, Source::Flag flags)
60         : Source(s, DataType::MIDI, name, flags)
61         , _writing(false)
62         , _model_iter_valid(false)
63         , _length_beats(0.0)
64         , _last_read_end(0)
65         , _capture_length(0)
66         , _capture_loop_length(0)
67 {
68 }
69
70 MidiSource::MidiSource (Session& s, const XMLNode& node)
71         : Source(s, node)
72         , _writing(false)
73         , _model_iter_valid(false)
74         , _length_beats(0.0)
75         , _last_read_end(0)
76         , _capture_length(0)
77         , _capture_loop_length(0)
78 {
79         if (set_state (node, Stateful::loading_state_version)) {
80                 throw failed_constructor();
81         }
82 }
83
84 MidiSource::~MidiSource ()
85 {
86 }
87
88 XMLNode&
89 MidiSource::get_state ()
90 {
91         XMLNode& node (Source::get_state());
92
93         if (_captured_for.length()) {
94                 node.add_property ("captured-for", _captured_for);
95         }
96
97         for (InterpolationStyleMap::const_iterator i = _interpolation_style.begin(); i != _interpolation_style.end(); ++i) {
98                 XMLNode* child = node.add_child (X_("InterpolationStyle"));
99                 child->add_property (X_("parameter"), EventTypeMap::instance().to_symbol (i->first));
100                 child->add_property (X_("style"), enum_2_string (i->second));
101         }
102
103         for (AutomationStateMap::const_iterator i = _automation_state.begin(); i != _automation_state.end(); ++i) {
104                 XMLNode* child = node.add_child (X_("AutomationState"));
105                 child->add_property (X_("parameter"), EventTypeMap::instance().to_symbol (i->first));
106                 child->add_property (X_("state"), enum_2_string (i->second));
107         }
108
109         return node;
110 }
111
112 int
113 MidiSource::set_state (const XMLNode& node, int /*version*/)
114 {
115         const XMLProperty* prop;
116         if ((prop = node.property ("captured-for")) != 0) {
117                 _captured_for = prop->value();
118         }
119
120         XMLNodeList children = node.children ();
121         for (XMLNodeConstIterator i = children.begin(); i != children.end(); ++i) {
122                 if ((*i)->name() == X_("InterpolationStyle")) {
123                         if ((prop = (*i)->property (X_("parameter"))) == 0) {
124                                 error << _("Missing parameter property on InterpolationStyle") << endmsg;
125                                 return -1;
126                         }
127                         Evoral::Parameter p = EventTypeMap::instance().from_symbol (prop->value());
128
129                         if ((prop = (*i)->property (X_("style"))) == 0) {
130                                 error << _("Missing style property on InterpolationStyle") << endmsg;
131                                 return -1;
132                         }
133                         Evoral::ControlList::InterpolationStyle s = static_cast<Evoral::ControlList::InterpolationStyle>(
134                                 string_2_enum (prop->value(), s));
135                         set_interpolation_of (p, s);
136
137                 } else if ((*i)->name() == X_("AutomationState")) {
138                         if ((prop = (*i)->property (X_("parameter"))) == 0) {
139                                 error << _("Missing parameter property on AutomationState") << endmsg;
140                                 return -1;
141                         }
142                         Evoral::Parameter p = EventTypeMap::instance().from_symbol (prop->value());
143
144                         if ((prop = (*i)->property (X_("state"))) == 0) {
145                                 error << _("Missing state property on AutomationState") << endmsg;
146                                 return -1;
147                         }
148                         AutoState s = static_cast<AutoState> (string_2_enum (prop->value(), s));
149                         set_automation_state_of (p, s);
150                 }
151         }
152
153         return 0;
154 }
155
156 bool
157 MidiSource::empty () const
158 {
159         return !_length_beats;
160 }
161
162 framecnt_t
163 MidiSource::length (framepos_t pos) const
164 {
165         if (!_length_beats) {
166                 return 0;
167         }
168
169         BeatsFramesConverter converter(_session.tempo_map(), pos);
170         return converter.to(_length_beats);
171 }
172
173 void
174 MidiSource::update_length (framecnt_t)
175 {
176         // You're not the boss of me!
177 }
178
179 void
180 MidiSource::invalidate ()
181 {
182         _model_iter_valid = false;
183         _model_iter.invalidate();
184 }
185
186 framecnt_t
187 MidiSource::midi_read (Evoral::EventSink<framepos_t>&     dst,
188                        framepos_t                         source_start,
189                        framepos_t                         start,
190                        framecnt_t                         cnt,
191                        MidiStateTracker*                  tracker,
192                        const std::set<Evoral::Parameter>& filtered) const
193 {
194         Glib::Threads::Mutex::Lock lm (_lock);
195
196         BeatsFramesConverter converter(_session.tempo_map(), source_start);
197
198         DEBUG_TRACE (DEBUG::MidiSourceIO,
199                      string_compose ("MidiSource::midi_read() %5 sstart %1 start %2 cnt %3 tracker %4\n",
200                                      source_start, start, cnt, tracker, name()));
201
202         if (_model) {
203                 // Find appropriate model iterator
204                 Evoral::Sequence<Evoral::MusicalTime>::const_iterator& i = _model_iter;
205                 if (_last_read_end == 0 || start != _last_read_end || !_model_iter_valid) {
206                         // Cached iterator is invalid, search for the first event past start
207                         i                 = _model->begin(converter.from(start), false, filtered);
208                         _model_iter_valid = true;
209                 }
210
211                 _last_read_end = start + cnt;
212
213                 // Copy events in [start, start + cnt) into dst
214                 for (; i != _model->end(); ++i) {
215                         const framecnt_t time_frames = converter.to(i->time());
216                         if (time_frames < start + cnt) {
217                                 // Offset by source start to convert event time to session time
218                                 dst.write (time_frames + source_start, i->event_type(), i->size(), i->buffer());
219
220                                 DEBUG_TRACE (DEBUG::MidiSourceIO,
221                                              string_compose ("%1: add event @ %2 type %3 size %4\n",
222                                                              _name, time_frames + source_start, i->event_type(), i->size()));
223
224                                 if (tracker) {
225                                         tracker->track (*i);
226                                 }
227                         } else {
228                                 DEBUG_TRACE (DEBUG::MidiSourceIO,
229                                              string_compose ("%1: reached end with event @ %2 vs. %3\n",
230                                                              _name, time_frames, start+cnt));
231                                 break;
232                         }
233                 }
234                 return cnt;
235         } else {
236                 return read_unlocked (dst, source_start, start, cnt, tracker);
237         }
238 }
239
240 framecnt_t
241 MidiSource::midi_write (MidiRingBuffer<framepos_t>& source,
242                         framepos_t                  source_start,
243                         framecnt_t                  cnt)
244 {
245         Glib::Threads::Mutex::Lock lm (_lock);
246
247         const framecnt_t ret = write_unlocked (source, source_start, cnt);
248
249         if (cnt == max_framecnt) {
250                 _last_read_end = 0;
251                 invalidate();
252         } else {
253                 _capture_length += cnt;
254         }
255
256         return ret;
257 }
258
259 void
260 MidiSource::mark_streaming_midi_write_started (NoteMode mode)
261 {
262         if (_model) {
263                 _model->set_note_mode (mode);
264                 _model->start_write ();
265         }
266
267         _writing = true;
268 }
269
270 void
271 MidiSource::mark_write_starting_now (framecnt_t position,
272                                      framecnt_t capture_length,
273                                      framecnt_t loop_length)
274 {
275         /* I'm not sure if this is the best way to approach this, but
276            _capture_length needs to be set up with the transport frame
277            when a record actually starts, as it is used by
278            SMFSource::write_unlocked to decide whether incoming notes
279            are within the correct time range.
280            mark_streaming_midi_write_started (perhaps a more logical
281            place to do this) is not called at exactly the time when
282            record starts, and I don't think it necessarily can be
283            because it is not RT-safe.
284         */
285
286         set_timeline_position(position);
287         _capture_length      = capture_length;
288         _capture_loop_length = loop_length;
289
290         BeatsFramesConverter converter(_session.tempo_map(), position);
291         _length_beats = converter.from(capture_length);
292 }
293
294 void
295 MidiSource::mark_streaming_write_started ()
296 {
297         NoteMode note_mode = _model ? _model->note_mode() : Sustained;
298         mark_streaming_midi_write_started (note_mode);
299 }
300
301 void
302 MidiSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption option,
303                                                  Evoral::MusicalTime                                    end)
304 {
305         if (_model) {
306                 _model->end_write (option, end);
307
308                 /* Make captured controls discrete to play back user input exactly. */
309                 for (MidiModel::Controls::iterator i = _model->controls().begin(); i != _model->controls().end(); ++i) {
310                         if (i->second->list()) {
311                                 i->second->list()->set_interpolation(Evoral::ControlList::Discrete);
312                                 _interpolation_style.insert(std::make_pair(i->second->parameter(), Evoral::ControlList::Discrete));
313                         }
314                 }
315         }
316
317         _writing = false;
318 }
319
320 void
321 MidiSource::mark_streaming_write_completed ()
322 {
323         mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
324 }
325
326 int
327 MidiSource::write_to (boost::shared_ptr<MidiSource> newsrc, Evoral::MusicalTime begin, Evoral::MusicalTime end)
328 {
329         newsrc->set_timeline_position (_timeline_position);
330         newsrc->copy_interpolation_from (this);
331         newsrc->copy_automation_state_from (this);
332
333         if (_model) {
334                 if (begin == Evoral::MinMusicalTime && end == Evoral::MaxMusicalTime) {
335                         _model->write_to (newsrc);
336                 } else {
337                         _model->write_section_to (newsrc, begin, end);
338                 }
339         } else {
340                 error << string_compose (_("programming error: %1"), X_("no model for MidiSource during ::clone()"));
341                 return -1;
342         }
343
344         newsrc->flush_midi();
345
346         /* force a reload of the model if the range is partial */
347
348         if (begin != Evoral::MinMusicalTime || end != Evoral::MaxMusicalTime) {
349                 newsrc->load_model (true, true);
350         } else {
351                 newsrc->set_model (_model);
352         }
353
354         /* this file is not removable (but since it is MIDI, it is mutable) */
355
356         boost::dynamic_pointer_cast<FileSource> (newsrc)->prevent_deletion ();
357
358         return 0;
359 }
360
361 void
362 MidiSource::session_saved()
363 {
364         /* this writes a copy of the data to disk.
365            XXX do we need to do this every time?
366         */
367
368         if (_model && _model->edited()) {
369                 /* The model is edited, write its contents into the current source
370                    file (overwiting previous contents). */
371
372                 /* Temporarily drop our reference to the model so that as the model
373                    pushes its current state to us, we don't try to update it. */
374                 boost::shared_ptr<MidiModel> mm = _model;
375                 _model.reset ();
376
377                 /* Flush model contents to disk. */
378                 mm->sync_to_source ();
379
380                 /* Reacquire model. */
381                 _model = mm;
382
383         } else {
384                 flush_midi();
385         }
386 }
387
388 void
389 MidiSource::set_note_mode(NoteMode mode)
390 {
391         if (_model) {
392                 _model->set_note_mode(mode);
393         }
394 }
395
396 void
397 MidiSource::drop_model ()
398 {
399         _model.reset();
400         invalidate();
401         ModelChanged (); /* EMIT SIGNAL */
402 }
403
404 void
405 MidiSource::set_model (boost::shared_ptr<MidiModel> m)
406 {
407         _model = m;
408         invalidate();
409         ModelChanged (); /* EMIT SIGNAL */
410 }
411
412 Evoral::ControlList::InterpolationStyle
413 MidiSource::interpolation_of (Evoral::Parameter p) const
414 {
415         InterpolationStyleMap::const_iterator i = _interpolation_style.find (p);
416         if (i == _interpolation_style.end()) {
417                 return EventTypeMap::instance().interpolation_of (p);
418         }
419
420         return i->second;
421 }
422
423 AutoState
424 MidiSource::automation_state_of (Evoral::Parameter p) const
425 {
426         AutomationStateMap::const_iterator i = _automation_state.find (p);
427         if (i == _automation_state.end()) {
428                 /* default to `play', otherwise if MIDI is recorded /
429                    imported with controllers etc. they are by default
430                    not played back, which is a little surprising.
431                 */
432                 return Play;
433         }
434
435         return i->second;
436 }
437
438 /** Set interpolation style to be used for a given parameter.  This change will be
439  *  propagated to anyone who needs to know.
440  */
441 void
442 MidiSource::set_interpolation_of (Evoral::Parameter p, Evoral::ControlList::InterpolationStyle s)
443 {
444         if (interpolation_of (p) == s) {
445                 return;
446         }
447
448         if (EventTypeMap::instance().interpolation_of (p) == s) {
449                 /* interpolation type is being set to the default, so we don't need a note in our map */
450                 _interpolation_style.erase (p);
451         } else {
452                 _interpolation_style[p] = s;
453         }
454
455         InterpolationChanged (p, s); /* EMIT SIGNAL */
456 }
457
458 void
459 MidiSource::set_automation_state_of (Evoral::Parameter p, AutoState s)
460 {
461         if (automation_state_of (p) == s) {
462                 return;
463         }
464
465         if (s == Play) {
466                 /* automation state is being set to the default, so we don't need a note in our map */
467                 _automation_state.erase (p);
468         } else {
469                 _automation_state[p] = s;
470         }
471
472         AutomationStateChanged (p, s); /* EMIT SIGNAL */
473 }
474
475 void
476 MidiSource::copy_interpolation_from (boost::shared_ptr<MidiSource> s)
477 {
478         copy_interpolation_from (s.get ());
479 }
480
481 void
482 MidiSource::copy_automation_state_from (boost::shared_ptr<MidiSource> s)
483 {
484         copy_automation_state_from (s.get ());
485 }
486
487 void
488 MidiSource::copy_interpolation_from (MidiSource* s)
489 {
490         _interpolation_style = s->_interpolation_style;
491
492         /* XXX: should probably emit signals here */
493 }
494
495 void
496 MidiSource::copy_automation_state_from (MidiSource* s)
497 {
498         _automation_state = s->_automation_state;
499
500         /* XXX: should probably emit signals here */
501 }