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