First stage of options rework.
[ardour.git] / libs / ardour / midi_track.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3         By Dave Robillard, 2006
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 #include "pbd/error.h"
20 #include <sigc++/retype.h>
21 #include <sigc++/retype_return.h>
22 #include <sigc++/bind.h>
23
24 #include "pbd/enumwriter.h"
25 #include "midi++/events.h"
26 #include "evoral/midi_util.h"
27
28 #include "ardour/amp.h"
29 #include "ardour/buffer_set.h"
30 #include "ardour/io_processor.h"
31 #include "ardour/meter.h"
32 #include "ardour/midi_diskstream.h"
33 #include "ardour/midi_playlist.h"
34 #include "ardour/midi_region.h"
35 #include "ardour/midi_source.h"
36 #include "ardour/midi_track.h"
37 #include "ardour/panner.h"
38 #include "ardour/processor.h"
39 #include "ardour/route_group_specialized.h"
40 #include "ardour/session.h"
41 #include "ardour/utils.h"
42
43 #include "i18n.h"
44
45 using namespace std;
46 using namespace ARDOUR;
47 using namespace PBD;
48
49 MidiTrack::MidiTrack (Session& sess, string name, Route::Flag flag, TrackMode mode)
50         : Track (sess, name, flag, mode, DataType::MIDI)
51         , _immediate_events(1024) // FIXME: size?
52         , _note_mode(Sustained)
53 {
54         use_new_diskstream ();
55
56         _declickable = true;
57         _freeze_record.state = NoFreeze;
58         _saved_meter_point = _meter_point;
59         _mode = mode;
60
61         set_input_minimum(ChanCount(DataType::MIDI, 1));
62         set_input_maximum(ChanCount(DataType::MIDI, 1));
63 }
64
65 MidiTrack::MidiTrack (Session& sess, const XMLNode& node)
66         : Track (sess, node, DataType::MIDI )
67         , _immediate_events(1024) // FIXME: size?
68         , _note_mode(Sustained)
69 {
70         _set_state(node, false);
71         
72         set_input_minimum(ChanCount(DataType::MIDI, 1));
73         set_input_maximum(ChanCount(DataType::MIDI, 1));
74 }
75
76 MidiTrack::~MidiTrack ()
77 {
78 }
79
80 void
81 MidiTrack::use_new_diskstream ()
82 {
83         MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
84
85         if (_flags & Hidden) {
86                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
87         } else {
88                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Recordable);
89         }
90
91         assert(_mode != Destructive);
92
93         boost::shared_ptr<MidiDiskstream> ds (new MidiDiskstream (_session, name(), dflags));
94         _session.add_diskstream (ds);
95
96         set_diskstream (boost::dynamic_pointer_cast<MidiDiskstream> (ds));
97 }       
98
99 int
100 MidiTrack::set_diskstream (boost::shared_ptr<MidiDiskstream> ds)
101 {
102         _diskstream = ds;
103         _diskstream->set_io (*this);
104         _diskstream->set_destructive (_mode == Destructive);
105
106         _diskstream->set_record_enabled (false);
107         //_diskstream->monitor_input (false);
108
109         ic_connection.disconnect();
110         ic_connection = input_changed.connect (mem_fun (*_diskstream, &MidiDiskstream::handle_input_change));
111
112         DiskstreamChanged (); /* EMIT SIGNAL */
113
114         return 0;
115 }       
116
117 int 
118 MidiTrack::use_diskstream (string name)
119 {
120         boost::shared_ptr<MidiDiskstream> dstream;
121
122         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream>(_session.diskstream_by_name (name))) == 0) {
123                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), name) << endmsg;
124                 return -1;
125         }
126         
127         return set_diskstream (dstream);
128 }
129
130 int 
131 MidiTrack::use_diskstream (const PBD::ID& id)
132 {
133         boost::shared_ptr<MidiDiskstream> dstream;
134
135         if ((dstream = boost::dynamic_pointer_cast<MidiDiskstream> (_session.diskstream_by_id (id))) == 0) {
136                 error << string_compose(_("MidiTrack: midi diskstream \"%1\" not known by session"), id) << endmsg;
137                 return -1;
138         }
139         
140         return set_diskstream (dstream);
141 }
142
143 boost::shared_ptr<MidiDiskstream>
144 MidiTrack::midi_diskstream() const
145 {
146         return boost::dynamic_pointer_cast<MidiDiskstream>(_diskstream);
147 }
148
149 int
150 MidiTrack::set_state (const XMLNode& node)
151 {
152         return _set_state (node, true);
153 }
154
155 int
156 MidiTrack::_set_state (const XMLNode& node, bool call_base)
157 {
158         const XMLProperty *prop;
159         XMLNodeConstIterator iter;
160
161         if (Route::_set_state (node, call_base)) {
162                 return -1;
163         }
164         
165         // No destructive MIDI tracks (yet?)
166         _mode = Normal;
167         
168         if ((prop = node.property (X_("note-mode"))) != 0) {
169                 _note_mode = NoteMode (string_2_enum (prop->value(), _note_mode));
170         } else {
171                 _note_mode = Sustained;
172         }
173
174         if ((prop = node.property ("diskstream-id")) == 0) {
175                 
176                 /* some old sessions use the diskstream name rather than the ID */
177
178                 if ((prop = node.property ("diskstream")) == 0) {
179                         fatal << _("programming error: MidiTrack given state without diskstream!") << endmsg;
180                         /*NOTREACHED*/
181                         return -1;
182                 }
183
184                 if (use_diskstream (prop->value())) {
185                         return -1;
186                 }
187
188         } else {
189                 
190                 PBD::ID id (prop->value());
191                 PBD::ID zero ("0");
192                 
193                 /* this wierd hack is used when creating tracks from a template. there isn't
194                    a particularly good time to interpose between setting the first part of
195                    the track state (notably Route::set_state() and the track mode), and the
196                    second part (diskstream stuff). So, we have a special ID for the diskstream
197                    that means "you should create a new diskstream here, not look for
198                    an old one.
199                 */
200                 
201                 if (id == zero) {
202                         use_new_diskstream ();
203                 } else if (use_diskstream (id)) {
204                         return -1;
205                 }
206         }
207
208         XMLNodeList nlist;
209         XMLNodeConstIterator niter;
210         XMLNode *child;
211
212         nlist = node.children();
213         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
214                 child = *niter;
215
216                 if (child->name() == X_("recenable")) {
217                         _rec_enable_control->set_state (*child);
218                         _session.add_controllable (_rec_enable_control);
219                 }
220         }
221
222         pending_state = const_cast<XMLNode*> (&node);
223
224         if (_session.state_of_the_state() & Session::Loading) {
225                 _session.StateReady.connect (mem_fun (*this, &MidiTrack::set_state_part_two));
226         } else {
227                 set_state_part_two ();
228         }
229
230         return 0;
231 }
232
233 XMLNode& 
234 MidiTrack::state(bool full_state)
235 {
236         XMLNode& root (Route::state(full_state));
237         XMLNode* freeze_node;
238         char buf[64];
239
240         if (_freeze_record.playlist) {
241                 XMLNode* inode;
242
243                 freeze_node = new XMLNode (X_("freeze-info"));
244                 freeze_node->add_property ("playlist", _freeze_record.playlist->name());
245                 freeze_node->add_property ("state", enum_2_string (_freeze_record.state));
246
247                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
248                         inode = new XMLNode (X_("processor"));
249                         (*i)->id.print (buf, sizeof(buf));
250                         inode->add_property (X_("id"), buf);
251                         inode->add_child_copy ((*i)->state);
252                 
253                         freeze_node->add_child_nocopy (*inode);
254                 }
255
256                 root.add_child_nocopy (*freeze_node);
257         }
258
259         /* Alignment: act as a proxy for the diskstream */
260         
261         XMLNode* align_node = new XMLNode (X_("Alignment"));
262         AlignStyle as = _diskstream->alignment_style ();
263         align_node->add_property (X_("style"), enum_2_string (as));
264         root.add_child_nocopy (*align_node);
265
266         root.add_property (X_("note-mode"), enum_2_string (_note_mode));
267         
268         /* we don't return diskstream state because we don't
269            own the diskstream exclusively. control of the diskstream
270            state is ceded to the Session, even if we create the
271            diskstream.
272         */
273
274         _diskstream->id().print (buf, sizeof(buf));
275         root.add_property ("diskstream-id", buf);
276         
277         root.add_child_nocopy (_rec_enable_control->get_state());
278
279         return root;
280 }
281
282 void
283 MidiTrack::set_state_part_two ()
284 {
285         XMLNode* fnode;
286         XMLProperty* prop;
287         LocaleGuard lg (X_("POSIX"));
288
289         /* This is called after all session state has been restored but before
290            have been made ports and connections are established.
291         */
292
293         if (pending_state == 0) {
294                 return;
295         }
296
297         if ((fnode = find_named_node (*pending_state, X_("freeze-info"))) != 0) {
298
299                 _freeze_record.state = Frozen;
300                 
301                 for (vector<FreezeRecordProcessorInfo*>::iterator i = _freeze_record.processor_info.begin(); i != _freeze_record.processor_info.end(); ++i) {
302                         delete *i;
303                 }
304                 _freeze_record.processor_info.clear ();
305                 
306                 if ((prop = fnode->property (X_("playlist"))) != 0) {
307                         boost::shared_ptr<Playlist> pl = _session.playlist_by_name (prop->value());
308                         if (pl) {
309                                 _freeze_record.playlist = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
310                         } else {
311                                 _freeze_record.playlist.reset();
312                                 _freeze_record.state = NoFreeze;
313                         return;
314                         }
315                 }
316                 
317                 if ((prop = fnode->property (X_("state"))) != 0) {
318                         _freeze_record.state = FreezeState (string_2_enum (prop->value(), _freeze_record.state));
319                 }
320                 
321                 XMLNodeConstIterator citer;
322                 XMLNodeList clist = fnode->children();
323                 
324                 for (citer = clist.begin(); citer != clist.end(); ++citer) {
325                         if ((*citer)->name() != X_("processor")) {
326                                 continue;
327                         }
328                         
329                         if ((prop = (*citer)->property (X_("id"))) == 0) {
330                                 continue;
331                         }
332                         
333                         FreezeRecordProcessorInfo* frii = new FreezeRecordProcessorInfo (*((*citer)->children().front()),
334                                                                                    boost::shared_ptr<Processor>());
335                         frii->id = prop->value ();
336                         _freeze_record.processor_info.push_back (frii);
337                 }
338         }
339
340         /* Alignment: act as a proxy for the diskstream */
341
342         if ((fnode = find_named_node (*pending_state, X_("Alignment"))) != 0) {
343
344                 if ((prop = fnode->property (X_("style"))) != 0) {
345
346                         /* fix for older sessions from before EnumWriter */
347
348                         string pstr;
349
350                         if (prop->value() == "capture") {
351                                 pstr = "CaptureTime";
352                         } else if (prop->value() == "existing") {
353                                 pstr = "ExistingMaterial";
354                         } else {
355                                 pstr = prop->value();
356                         }
357
358                         AlignStyle as = AlignStyle (string_2_enum (pstr, as));
359                         _diskstream->set_persistent_align_style (as);
360                 }
361         }
362         return;
363 }       
364
365 int
366 MidiTrack::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
367                  bool can_record, bool rec_monitors_input)
368 {
369         int dret;
370         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
371         
372         prepare_inputs (nframes);
373
374         {
375                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
376                 if (lm.locked()) {
377                         // automation snapshot can also be called from the non-rt context
378                         // and it uses the redirect list, so we take the lock out here
379                         automation_snapshot (start_frame);
380                 }
381         }
382
383         if (n_outputs().n_total() == 0 && _processors.empty()) {
384                 return 0;
385         }
386
387         if (!_active) {
388                 silence (nframes);
389                 return 0;
390         }
391
392         nframes_t transport_frame = _session.transport_frame();
393
394         
395         if ((nframes = check_initial_delay (nframes, transport_frame)) == 0) {
396                 /* need to do this so that the diskstream sets its
397                    playback distance to zero, thus causing diskstream::commit
398                    to do nothing.
399                    */
400                 return diskstream->process (transport_frame, 0, can_record, rec_monitors_input);
401         } 
402
403         _silent = false;
404
405         if ((dret = diskstream->process (transport_frame, nframes, can_record, rec_monitors_input)) != 0) {
406
407                 silence (nframes);
408                 return dret;
409         }
410
411         /* special condition applies */
412
413         if (_meter_point == MeterInput) {
414                 just_meter_input (start_frame, end_frame, nframes);
415         }
416
417         if (diskstream->record_enabled() && !can_record && !_session.config.get_auto_input()) {
418
419                 /* not actually recording, but we want to hear the input material anyway,
420                    at least potentially (depending on monitoring options)
421                    */
422
423                 passthru (start_frame, end_frame, nframes, 0);
424
425         } else {
426                 /*
427                    XXX is it true that the earlier test on n_outputs()
428                    means that we can avoid checking it again here? i think
429                    so, because changing the i/o configuration of an IO
430                    requires holding the AudioEngine lock, which we hold
431                    while in the process() tree.
432                    */
433
434
435                 /* copy the diskstream data to all output buffers */
436
437                 //const size_t limit = n_process_buffers().n_audio();
438                 BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
439
440                 diskstream->get_playback(bufs.get_midi(0), start_frame, end_frame);
441
442                 process_output_buffers (bufs, start_frame, end_frame, nframes,
443                                 (!_session.get_record_enabled() || !Config->get_do_not_record_plugins()), declick);
444         
445         }
446
447         flush_outputs (nframes);
448
449         return 0;
450 }
451
452 void
453 MidiTrack::write_controller_messages(MidiBuffer& output_buf, sframes_t start, sframes_t end, nframes_t nframes)
454 {
455         // Append immediate events (UI controls)
456
457         // XXX TAKE _port_offset in Port into account???
458
459         _immediate_events.read (output_buf, 0, 0, nframes - 1); // all stamps = 0
460 }
461
462 int
463 MidiTrack::export_stuff (BufferSet& bufs, nframes_t nframes, sframes_t end_frame)
464 {
465         return -1;
466 }
467
468 void
469 MidiTrack::set_latency_delay (nframes_t longest_session_latency)
470 {
471         Route::set_latency_delay (longest_session_latency);
472         _diskstream->set_roll_delay (_roll_delay);
473 }
474
475 boost::shared_ptr<Region>
476 MidiTrack::bounce (InterThreadInfo& itt)
477 {
478         throw;
479         // vector<MidiSource*> srcs;
480         // return _session.write_one_track (*this, 0, _session.current_end_frame(), false, srcs, itt);
481         return boost::shared_ptr<Region> ();
482 }
483
484
485 boost::shared_ptr<Region>
486 MidiTrack::bounce_range (nframes_t start, nframes_t end, InterThreadInfo& itt, bool enable_processing)
487 {
488         throw;
489         //vector<MidiSource*> srcs;
490         //return _session.write_one_track (*this, start, end, false, srcs, itt);
491         return boost::shared_ptr<Region> ();
492 }
493
494 void
495 MidiTrack::freeze (InterThreadInfo& itt)
496 {
497 }
498
499 void
500 MidiTrack::unfreeze ()
501 {
502         _freeze_record.state = UnFrozen;
503         FreezeChange (); /* EMIT SIGNAL */
504 }
505
506 void
507 MidiTrack::set_note_mode (NoteMode m)
508 {
509         _note_mode = m;
510         midi_diskstream()->set_note_mode(m);
511 }
512
513 void
514 MidiTrack::midi_panic() 
515 {
516         for (uint8_t channel = 0; channel <= 0xF; channel++) {
517                 uint8_t ev[3] = { MIDI_CMD_CONTROL | channel, MIDI_CTL_SUSTAIN, 0 };
518                 write_immediate_event(3, ev);
519                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
520                 write_immediate_event(3, ev);
521                 ev[1] = MIDI_CTL_RESET_CONTROLLERS;
522                 write_immediate_event(3, ev);
523         }
524 }
525
526 /** \return true on success, false on failure (no buffer space left)
527  */
528 bool
529 MidiTrack::write_immediate_event(size_t size, const uint8_t* buf)
530 {
531         if (!Evoral::midi_event_is_valid(buf, size)) {
532                 cerr << "WARNING: Ignoring illegal immediate MIDI event" << endl;
533                 return false;
534         }
535         const uint32_t type = EventTypeMap::instance().midi_event_type(buf[0]);
536         return (_immediate_events.write(0, type, size, buf) == size);
537 }
538
539 void
540 MidiTrack::MidiControl::set_value(float val)
541 {
542         bool valid = false;
543         if (isinf(val)) {
544                 cerr << "MIDIControl value is infinity" << endl;
545         } else if (isnan(val)) {
546                 cerr << "MIDIControl value is NaN" << endl;
547         } else if (val < _list->parameter().min()) {
548                 cerr << "MIDIControl value is < " << _list->parameter().min() << endl;
549         } else if (val > _list->parameter().max()) {
550                 cerr << "MIDIControl value is > " << _list->parameter().max() << endl;
551         } else {
552                 valid = true;
553         }
554         
555         if (!valid) {
556                 return;
557         }
558
559         assert(val <= _list->parameter().max());
560         size_t size = 3;
561
562         if ( ! automation_playback()) {
563                 uint8_t ev[3] = { _list->parameter().channel(), int(val), 0 };
564                 switch(_list->parameter().type()) {
565                 case MidiCCAutomation:
566                         ev[0] += MIDI_CMD_CONTROL;
567                         ev[1] = _list->parameter().id();
568                         ev[2] = int(val);
569                         break;
570                         
571                 case MidiPgmChangeAutomation:
572                         size = 2;
573                         ev[0] += MIDI_CMD_PGM_CHANGE;
574                         ev[1] = int(val);
575                         break;
576                         
577                 case MidiChannelPressureAutomation:
578                         size = 2;
579                         ev[0] += MIDI_CMD_CHANNEL_PRESSURE;
580                         ev[1] = int(val);
581                         break;
582                         
583                 case MidiPitchBenderAutomation:
584                         ev[0] += MIDI_CMD_BENDER;
585                         ev[1] = 0x7F & int(val);
586                         ev[2] = 0x7F & (int(val) >> 7);
587                         break;
588                         
589                 default:
590                         assert(false);
591                 }
592                 _route->write_immediate_event(size,  ev);
593         }
594
595         AutomationControl::set_value(val);
596
597