faderport: cleanup
[ardour.git] / libs / surfaces / faderport / faderport.cc
1 /*
2     Copyright (C) 2015 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <cstdlib>
21 #include <sstream>
22 #include <algorithm>
23
24 #include <stdint.h>
25
26 #include <glibmm/fileutils.h>
27 #include <glibmm/miscutils.h>
28
29 #include "pbd/controllable_descriptor.h"
30 #include "pbd/error.h"
31 #include "pbd/failed_constructor.h"
32 #include "pbd/file_utils.h"
33 #include "pbd/pthread_utils.h"
34 #include "pbd/compose.h"
35 #include "pbd/xml++.h"
36
37 #include "midi++/port.h"
38
39 #include "ardour/async_midi_port.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/amp.h"
42 #include "ardour/debug.h"
43 #include "ardour/filesystem_paths.h"
44 #include "ardour/midi_port.h"
45 #include "ardour/midiport_manager.h"
46 #include "ardour/monitor_processor.h"
47 #include "ardour/profile.h"
48 #include "ardour/rc_configuration.h"
49 #include "ardour/route.h"
50 #include "ardour/session.h"
51 #include "ardour/track.h"
52
53 #include "faderport.h"
54
55 using namespace ARDOUR;
56 using namespace ArdourSurface;
57 using namespace PBD;
58 using namespace Glib;
59 using namespace std;
60
61 #include "i18n.h"
62
63 #include "pbd/abstract_ui.cc" // instantiate template
64
65 FaderPort::FaderPort (Session& s)
66         : ControlProtocol (s, _("Faderport"))
67         , AbstractUI<FaderPortRequest> ("faderport")
68         , gui (0)
69         , connection_state (ConnectionState (0))
70         , _device_active (false)
71         , fader_msb (0)
72         , fader_lsb (0)
73         , fader_is_touched (false)
74         , button_state (ButtonState (0))
75         , blink_state (false)
76 {
77         last_encoder_time = 0;
78
79         boost::shared_ptr<ARDOUR::Port> inp;
80         boost::shared_ptr<ARDOUR::Port> outp;
81
82         inp  = AudioEngine::instance()->register_input_port (DataType::MIDI, "Faderport Recv", true);
83         outp = AudioEngine::instance()->register_output_port (DataType::MIDI, "Faderport Send", true);
84
85         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(inp);
86         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(outp);
87
88         if (_input_port == 0 || _output_port == 0) {
89                 throw failed_constructor();
90         }
91
92         TrackSelectionChanged.connect (selection_connection, MISSING_INVALIDATOR, boost::bind (&FaderPort::gui_track_selection_changed, this, _1), this);
93
94         /* Catch port connections and disconnections */
95         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&FaderPort::connection_handler, this, _1, _2, _3, _4, _5), this);
96
97         buttons.insert (std::make_pair (Mute, Button (*this, _("Mute"), Mute, 21)));
98         buttons.insert (std::make_pair (Solo, Button (*this, _("Solo"), Solo, 22)));
99         buttons.insert (std::make_pair (Rec, Button (*this, _("Rec"), Rec, 23)));
100         buttons.insert (std::make_pair (Left, Button (*this, _("Left"), Left, 20)));
101         buttons.insert (std::make_pair (Bank, Button (*this, _("Bank"), Bank, 19)));
102         buttons.insert (std::make_pair (Right, Button (*this, _("Right"), Right, 18)));
103         buttons.insert (std::make_pair (Output, Button (*this, _("Output"), Output, 17)));
104         buttons.insert (std::make_pair (FP_Read, Button (*this, _("Read"), FP_Read, 13)));
105         buttons.insert (std::make_pair (FP_Write, Button (*this, _("Write"), FP_Write, 14)));
106         buttons.insert (std::make_pair (FP_Touch, Button (*this, _("Touch"), FP_Touch, 15)));
107         buttons.insert (std::make_pair (FP_Off, Button (*this, _("Off"), FP_Off, 16)));
108         buttons.insert (std::make_pair (Mix, Button (*this, _("Mix"), Mix, 12)));
109         buttons.insert (std::make_pair (Proj, Button (*this, _("Proj"), Proj, 11)));
110         buttons.insert (std::make_pair (Trns, Button (*this, _("Trns"), Trns, 10)));
111         buttons.insert (std::make_pair (Undo, Button (*this, _("Undo"), Undo, 9)));
112         buttons.insert (std::make_pair (Shift, Button (*this, _("Shift"), Shift, 5)));
113         buttons.insert (std::make_pair (Punch, Button (*this, _("Punch"), Punch, 6)));
114         buttons.insert (std::make_pair (User, Button (*this, _("User"), User, 7)));
115         buttons.insert (std::make_pair (Loop, Button (*this, _("Loop"), Loop, 8)));
116         buttons.insert (std::make_pair (Rewind, Button (*this, _("Rewind"), Rewind, 4)));
117         buttons.insert (std::make_pair (Ffwd, Button (*this, _("Ffwd"), Ffwd, 3)));
118         buttons.insert (std::make_pair (Stop, Button (*this, _("Stop"), Stop, 2)));
119         buttons.insert (std::make_pair (Play, Button (*this, _("Play"), Play, 1)));
120         buttons.insert (std::make_pair (RecEnable, Button (*this, _("RecEnable"), RecEnable, 0)));
121         buttons.insert (std::make_pair (FaderTouch, Button (*this, _("Fader (touch)"), FaderTouch, -1)));
122
123         get_button (Left).set_action ( boost::bind (&FaderPort::left, this), true);
124         get_button (Right).set_action ( boost::bind (&FaderPort::right, this), true);
125
126         get_button (Undo).set_action (boost::bind (&FaderPort::undo, this), true);
127         get_button (Undo).set_action (boost::bind (&FaderPort::redo, this), true, ShiftDown);
128         get_button (Undo).set_flash (true);
129
130         get_button (FP_Read).set_action (boost::bind (&FaderPort::read, this), true);
131         get_button (FP_Write).set_action (boost::bind (&FaderPort::write, this), true);
132         get_button (FP_Touch).set_action (boost::bind (&FaderPort::touch, this), true);
133         get_button (FP_Off).set_action (boost::bind (&FaderPort::off, this), true);
134
135         get_button (Play).set_action (boost::bind (&BasicUI::transport_play, this, true), true);
136         get_button (RecEnable).set_action (boost::bind (&BasicUI::rec_enable_toggle, this), true);
137         /* Stop is a modifier, so we have to use its own button state to get
138            the default action (since StopDown will be set when looking for the
139            action to invoke.
140         */
141         get_button (Stop).set_action (boost::bind (&BasicUI::transport_stop, this), true, StopDown);
142         get_button (Ffwd).set_action (boost::bind (&BasicUI::ffwd, this), true);
143
144         /* See comments about Stop above .. */
145         get_button (Rewind).set_action (boost::bind (&BasicUI::rewind, this), true, RewindDown);
146         get_button (Rewind).set_action (boost::bind (&BasicUI::goto_zero, this), true, ButtonState (RewindDown|StopDown));
147         get_button (Rewind).set_action (boost::bind (&BasicUI::goto_start, this), true, ButtonState (RewindDown|ShiftDown));
148
149         get_button (Ffwd).set_action (boost::bind (&BasicUI::ffwd, this), true);
150         get_button (Ffwd).set_action (boost::bind (&BasicUI::goto_end, this), true, ShiftDown);
151
152         get_button (Loop).set_action (boost::bind (&BasicUI::loop_toggle, this), true);
153         get_button (Loop).set_action (boost::bind (&BasicUI::add_marker, this, string()), true, ShiftDown);
154
155         get_button (Punch).set_action (boost::bind (&BasicUI::prev_marker, this), true, ShiftDown);
156         get_button (User).set_action (boost::bind (&BasicUI::next_marker, this), true, ShiftDown);
157
158         get_button (Mute).set_action (boost::bind (&FaderPort::mute, this), true);
159         get_button (Solo).set_action (boost::bind (&FaderPort::solo, this), true);
160         get_button (Rec).set_action (boost::bind (&FaderPort::rec_enable, this), true);
161
162         get_button (Output).set_action (boost::bind (&FaderPort::use_master, this), true);
163         get_button (Output).set_action (boost::bind (&FaderPort::use_monitor, this), true, ShiftDown);
164 }
165
166 FaderPort::~FaderPort ()
167 {
168         if (_input_port) {
169                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("unregistering input port %1\n", boost::shared_ptr<ARDOUR::Port>(_input_port)->name()));
170                 AudioEngine::instance()->unregister_port (_input_port);
171                 _input_port.reset ();
172         }
173
174         if (_output_port) {
175 //              _output_port->drain (10000);  //ToDo:  is this necessary?  It hangs the shutdown, for me
176                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("unregistering output port %1\n", boost::shared_ptr<ARDOUR::Port>(_output_port)->name()));
177                 AudioEngine::instance()->unregister_port (_output_port);
178                 _output_port.reset ();
179         }
180
181         tear_down_gui ();
182 }
183
184 void
185 FaderPort::start_midi_handling ()
186 {
187         /* handle device inquiry response */
188         _input_port->parser()->sysex.connect_same_thread (midi_connections, boost::bind (&FaderPort::sysex_handler, this, _1, _2, _3));
189         /* handle buttons */
190         _input_port->parser()->poly_pressure.connect_same_thread (midi_connections, boost::bind (&FaderPort::button_handler, this, _1, _2));
191         /* handle encoder */
192         _input_port->parser()->pitchbend.connect_same_thread (midi_connections, boost::bind (&FaderPort::encoder_handler, this, _1, _2));
193         /* handle fader */
194         _input_port->parser()->controller.connect_same_thread (midi_connections, boost::bind (&FaderPort::fader_handler, this, _1, _2));
195
196         /* This connection means that whenever data is ready from the input
197          * port, the relevant thread will invoke our ::midi_input_handler()
198          * method, which will read the data, and invoke the parser.
199          */
200
201         _input_port->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &FaderPort::midi_input_handler), _input_port));
202         _input_port->xthread().attach (main_loop()->get_context());
203 }
204
205 void
206 FaderPort::stop_midi_handling ()
207 {
208         midi_connections.drop_connections ();
209
210         /* Note: the input handler is still active at this point, but we're no
211          * longer connected to any of the parser signals
212          */
213 }
214
215 void
216 FaderPort::do_request (FaderPortRequest* req)
217 {
218         if (req->type == CallSlot) {
219
220                 call_slot (MISSING_INVALIDATOR, req->the_slot);
221
222         } else if (req->type == Quit) {
223
224                 stop ();
225         }
226 }
227
228 int
229 FaderPort::stop ()
230 {
231         BaseUI::quit ();
232
233         return 0;
234 }
235
236 void
237 FaderPort::thread_init ()
238 {
239         struct sched_param rtparam;
240
241         pthread_set_name (X_("FaderPort"));
242
243         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("FaderPort"), 2048);
244         ARDOUR::SessionEvent::create_per_thread_pool (X_("FaderPort"), 128);
245
246         memset (&rtparam, 0, sizeof (rtparam));
247         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
248
249         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
250                 // do we care? not particularly.
251         }
252 }
253
254 void
255 FaderPort::all_lights_out ()
256 {
257         for (ButtonMap::iterator b = buttons.begin(); b != buttons.end(); ++b) {
258                 b->second.set_led_state (_output_port, false, true);
259         }
260 }
261
262 FaderPort::Button&
263 FaderPort::get_button (ButtonID id) const
264 {
265         ButtonMap::const_iterator b = buttons.find (id);
266         assert (b != buttons.end());
267         return const_cast<Button&>(b->second);
268 }
269
270 void
271 FaderPort::button_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
272 {
273         ButtonID id (ButtonID (tb->controller_number));
274         Button& button (get_button (id));
275
276         button.do_timing (tb->value ? true : false);
277
278         switch (id) {
279         case Shift:
280                 button_state = (tb->value ? ButtonState (button_state|ShiftDown) : ButtonState (button_state&~ShiftDown));
281                 break;
282         case Stop:
283                 button_state = (tb->value ? ButtonState (button_state|StopDown) : ButtonState (button_state&~StopDown));
284                 break;
285         case Rewind:
286                 button_state = (tb->value ? ButtonState (button_state|RewindDown) : ButtonState (button_state&~RewindDown));
287                 break;
288         case User:
289                 button_state = (tb->value ? ButtonState (button_state|UserDown) : ButtonState (button_state&~UserDown));
290                 break;
291         case FaderTouch:
292                 fader_is_touched = tb->value;
293                 if (_current_route) {
294                         boost::shared_ptr<AutomationControl> gain = _current_route->gain_control ();
295                         if (gain) {
296                                 framepos_t now = session->engine().sample_time();
297                                 if (tb->value) {
298                                         gain->start_touch (now);
299                                 } else {
300                                         gain->stop_touch (true, now);
301                                 }
302                         }
303                 }
304                 break;
305         default:
306                 break;
307         }
308
309         if (button.uses_flash()) {
310                 button.set_led_state (_output_port, (int)tb->value);
311         }
312
313         button.invoke (button_state, tb->value ? true : false);
314 }
315
316 void
317 FaderPort::encoder_handler (MIDI::Parser &, MIDI::pitchbend_t pb)
318 {
319         int delta = 1;
320
321         if (pb >= 8192) {
322                 delta = -1;
323         }
324
325         //knob debouncing and hysteresis.  The presonus encoder often sends bursts of events, or goes the wrong direction
326         {
327                 last_last_encoder_delta = last_encoder_delta;
328                 last_encoder_delta = delta;
329                 microseconds_t now = get_microseconds ();
330                 if ((now - last_encoder_time) < 10*1000) { //require at least 10ms interval between changes, because the device sometimes sends multiple deltas
331                         return;
332                 }
333                 if ((now - last_encoder_time) < 100*1000) { //avoid directional changes while "spinning", 100ms window
334                         if ( (delta == last_encoder_delta) && (delta == last_last_encoder_delta) ) {
335                                 last_good_encoder_delta = delta;  //3 in a row, grudgingly accept this as the new direction
336                         }
337                         if (delta != last_good_encoder_delta) {  //otherwise ensure we keep going the same way
338                                 delta = last_good_encoder_delta;
339                         }
340                 } else {  //we aren't yet in a spin window, just assume this move is really what we want
341                         //NOTE:  if you are worried about where these get initialized, here it is.
342                         last_last_encoder_delta = delta;
343                         last_encoder_delta = delta;
344                 }
345                 last_encoder_time = now;
346                 last_good_encoder_delta = delta;
347         }
348
349         if (_current_route) {
350
351                 ButtonState trim_modifier;
352                 ButtonState width_modifier;
353
354                 if (Profile->get_mixbus()) {
355                         trim_modifier = ShiftDown;
356                         width_modifier = ButtonState (0);
357                 } else {
358                         trim_modifier = UserDown;
359                         width_modifier = ShiftDown;
360                 }
361
362                 if ((button_state & trim_modifier) == trim_modifier ) {    // mod+encoder = input trim
363                         boost::shared_ptr<AutomationControl> gain = _current_route->trim()->gain_control ();
364                         if (gain) {
365                                 float val = gain->get_user();  //for gain elements, the "user" value is in dB
366                                 val += delta;
367                                 gain->set_user(val);
368                         }
369                 } else if (width_modifier && ((button_state & width_modifier) == width_modifier)) {
370                         ardour_pan_width (delta);
371
372                 } else {  // pan/balance
373                         if (!Profile->get_mixbus()) {
374                                 ardour_pan_azimuth (delta);
375                         } else {
376                                 mixbus_pan (delta);
377                         }
378                 }
379         }
380 }
381
382 void
383 FaderPort::fader_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
384 {
385         bool was_fader = false;
386
387         if (tb->controller_number == 0x0) {
388                 fader_msb = tb->value;
389                 was_fader = true;
390         } else if (tb->controller_number == 0x20) {
391                 fader_lsb = tb->value;
392                 was_fader = true;
393         }
394
395         if (was_fader) {
396                 if (_current_route) {
397                         boost::shared_ptr<AutomationControl> gain = _current_route->gain_control ();
398                         if (gain) {
399                                 int ival = (fader_msb << 7) | fader_lsb;
400                                 float val = gain->interface_to_internal (ival/16384.0);
401                                 _current_route->set_gain (val, this);
402                         }
403                 }
404         }
405 }
406
407 void
408 FaderPort::sysex_handler (MIDI::Parser &p, MIDI::byte *buf, size_t sz)
409 {
410         if (sz < 17) {
411                 return;
412         }
413
414         if (buf[2] != 0x7f ||
415             buf[3] != 0x06 ||
416             buf[4] != 0x02 ||
417             buf[5] != 0x0 ||
418             buf[6] != 0x1 ||
419             buf[7] != 0x06 ||
420             buf[8] != 0x02 ||
421             buf[9] != 0x0 ||
422             buf[10] != 0x01 ||
423             buf[11] != 0x0) {
424                 return;
425         }
426
427         _device_active = true;
428
429         DEBUG_TRACE (DEBUG::FaderPort, "FaderPort identified via MIDI Device Inquiry response\n");
430
431         /* put it into native mode */
432
433         MIDI::byte native[3];
434         native[0] = 0x91;
435         native[1] = 0x00;
436         native[2] = 0x64;
437
438         _output_port->write (native, 3, 0);
439
440         all_lights_out ();
441
442         /* catch up on state */
443
444         notify_transport_state_changed ();
445         notify_record_state_changed ();
446 }
447
448 int
449 FaderPort::set_active (bool yn)
450 {
451         DEBUG_TRACE (DEBUG::FaderPort, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
452
453         if (yn == active()) {
454                 return 0;
455         }
456
457         if (yn) {
458
459                 /* start event loop */
460
461                 BaseUI::run ();
462
463                 connect_session_signals ();
464
465                 Glib::RefPtr<Glib::TimeoutSource> blink_timeout = Glib::TimeoutSource::create (200); // milliseconds
466                 blink_connection = blink_timeout->connect (sigc::mem_fun (*this, &FaderPort::blink));
467                 blink_timeout->attach (main_loop()->get_context());
468
469         } else {
470
471                 BaseUI::quit ();
472                 close ();
473
474         }
475
476         ControlProtocol::set_active (yn);
477
478         DEBUG_TRACE (DEBUG::FaderPort, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
479
480         return 0;
481 }
482
483 bool
484 FaderPort::blink ()
485 {
486         blink_state = !blink_state;
487
488         for (Blinkers::iterator b = blinkers.begin(); b != blinkers.end(); b++) {
489                 get_button(*b).set_led_state (_output_port, blink_state);
490         }
491
492         return true;
493 }
494
495 void
496 FaderPort::close ()
497 {
498         all_lights_out ();
499
500         stop_midi_handling ();
501         session_connections.drop_connections ();
502         port_connection.disconnect ();
503         blink_connection.disconnect ();
504         selection_connection.disconnect ();
505         route_connections.drop_connections ();
506
507 #if 0
508         route_connections.drop_connections ();
509 #endif
510 }
511
512 void
513 FaderPort::notify_record_state_changed ()
514 {
515         switch (session->record_status()) {
516         case Session::Disabled:
517                 get_button (RecEnable).set_led_state (_output_port, false);
518                 blinkers.remove (RecEnable);
519                 break;
520         case Session::Enabled:
521                 get_button (RecEnable).set_led_state (_output_port, true);
522                 blinkers.push_back (RecEnable);
523                 break;
524         case Session::Recording:
525                 get_button (RecEnable).set_led_state (_output_port, true);
526                 blinkers.remove (RecEnable);
527                 break;
528         }
529 }
530
531 void
532 FaderPort::notify_transport_state_changed ()
533 {
534         get_button (Loop).set_led_state (_output_port, session->get_play_loop());
535         get_button (Play).set_led_state (_output_port, session->transport_speed() == 1.0);
536         get_button (Stop).set_led_state (_output_port, session->transport_stopped ());
537         get_button (Rewind).set_led_state (_output_port, session->transport_speed() < 0.0);
538         get_button (Ffwd).set_led_state (_output_port, session->transport_speed() > 1.0);
539 }
540
541 void
542 FaderPort::connect_session_signals()
543 {
544         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::notify_record_state_changed, this), this);
545         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::notify_transport_state_changed, this), this);
546 }
547
548 bool
549 FaderPort::midi_input_handler (Glib::IOCondition ioc, boost::shared_ptr<ARDOUR::AsyncMIDIPort> port)
550 {
551         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("something happend on  %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
552
553         if (ioc & ~IO_IN) {
554                 return false;
555         }
556
557         if (ioc & IO_IN) {
558
559                 if (port) {
560                         port->clear ();
561                 }
562
563                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("data available on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
564                 framepos_t now = session->engine().sample_time();
565                 port->parse (now);
566         }
567
568         return true;
569 }
570
571
572 XMLNode&
573 FaderPort::get_state ()
574 {
575         XMLNode& node (ControlProtocol::get_state());
576
577         XMLNode* child;
578
579         child = new XMLNode (X_("Input"));
580         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_input_port)->get_state());
581         node.add_child_nocopy (*child);
582
583
584         child = new XMLNode (X_("Output"));
585         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_output_port)->get_state());
586         node.add_child_nocopy (*child);
587
588         /* Save action state for Mix, Proj, Trns and User buttons, since these
589          * are user controlled. We can only save named-action operations, since
590          * internal functions are just pointers to functions and hard to
591          * serialize without enumerating them all somewhere.
592          */
593
594         node.add_child_nocopy (get_button (Mix).get_state());
595         node.add_child_nocopy (get_button (Proj).get_state());
596         node.add_child_nocopy (get_button (Trns).get_state());
597         node.add_child_nocopy (get_button (User).get_state());
598
599         return node;
600 }
601
602 int
603 FaderPort::set_state (const XMLNode& node, int version)
604 {
605         XMLNodeList nlist;
606         XMLNodeConstIterator niter;
607         XMLNode const* child;
608
609         if (ControlProtocol::set_state (node, version)) {
610                 return -1;
611         }
612
613         if ((child = node.child (X_("Input"))) != 0) {
614                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
615                 if (portnode) {
616                         boost::shared_ptr<ARDOUR::Port>(_input_port)->set_state (*portnode, version);
617                 }
618         }
619
620         if ((child = node.child (X_("Output"))) != 0) {
621                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
622                 if (portnode) {
623                         boost::shared_ptr<ARDOUR::Port>(_output_port)->set_state (*portnode, version);
624                 }
625         }
626
627         for (XMLNodeList::const_iterator n = node.children().begin(); n != node.children().end(); ++n) {
628                 if ((*n)->name() == X_("Button")) {
629                         XMLProperty const * prop = (*n)->property (X_("id"));
630                         if (!prop) {
631                                 continue;
632                         }
633                         int xid = atoi (prop->value());
634                         ButtonMap::iterator b = buttons.find (ButtonID (xid));
635                         if (b == buttons.end()) {
636                                 continue;
637                         }
638                         b->second.set_state (**n);
639                 }
640         }
641
642         return 0;
643 }
644
645 bool
646 FaderPort::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
647 {
648         if (!_input_port || !_output_port) {
649                 return false;
650         }
651
652         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
653         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
654
655         if (ni == name1 || ni == name2) {
656                 if (yn) {
657                         connection_state |= InputConnected;
658                 } else {
659                         connection_state &= ~InputConnected;
660                 }
661         } else if (no == name1 || no == name2) {
662                 if (yn) {
663                         connection_state |= OutputConnected;
664                 } else {
665                         connection_state &= ~OutputConnected;
666                 }
667         } else {
668                 /* not our ports */
669                 return false;
670         }
671
672         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
673
674                 /* XXX this is a horrible hack. Without a short sleep here,
675                    something prevents the device wakeup messages from being
676                    sent and/or the responses from being received.
677                 */
678
679                 g_usleep (100000);
680                 connected ();
681
682         } else {
683                 DEBUG_TRACE (DEBUG::FaderPort, "Device disconnected (input or output or both) or not yet fully connected\n");
684                 _device_active = false;
685         }
686
687         ConnectionChange (); /* emit signal for our GUI */
688
689         return true; /* connection status changed */
690 }
691
692 void
693 FaderPort::connected ()
694 {
695         DEBUG_TRACE (DEBUG::FaderPort, "connection status changed\n");
696
697         start_midi_handling ();
698
699         /* send device inquiry */
700
701         MIDI::byte buf[6];
702
703         buf[0] = 0xf0;
704         buf[1] = 0x7e;
705         buf[2] = 0x7f;
706         buf[3] = 0x06;
707         buf[4] = 0x01;
708         buf[5] = 0xf7;
709
710         _output_port->write (buf, 6, 0);
711 }
712
713 void
714 FaderPort::Button::invoke (FaderPort::ButtonState bs, bool press)
715 {
716         if (!press) {
717                 if (long_press == 1) {
718                         bs = FaderPort::ButtonState (bs | LongishPress);
719                 } else if (long_press == 2) {
720                         bs = FaderPort::ButtonState (bs | LongPress);
721                 }
722         }
723
724         ToDoMap::iterator x;
725
726         if (press) {
727                 if ((x = on_press.find (bs)) == on_press.end()) {
728                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("no press action for button %1 state %2%3\%4\n", id, hex, bs, dec));
729                         return;
730                 }
731         } else {
732                 if ((x = on_release.find (bs)) == on_release.end()) {
733                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("no release action for button %1 state %2%3\%4\n", id, hex, bs, dec));
734                         return;
735                 }
736         }
737
738         switch (x->second.type) {
739         case NamedAction:
740                 if (!x->second.action_name.empty()) {
741                         fp.access_action (x->second.action_name);
742                 }
743                 break;
744         case InternalFunction:
745                 if (x->second.function) {
746                         x->second.function ();
747                 }
748         }
749 }
750
751 void
752 FaderPort::Button::do_timing (bool press)
753 {
754         if (press) {
755                 pressed_at = get_microseconds ();
756                 long_press = 0;
757         } else {
758                 if (pressed_at > 0) {
759                         const ARDOUR::microseconds_t delta = ARDOUR::get_microseconds () - pressed_at;
760                         if (delta < 500000) {
761                                 long_press = 0;
762                         } else if (delta < 1000000) {
763                                 long_press = 1;
764                         } else {
765                                 long_press = 2;
766                         }
767                         pressed_at = 0;
768                 }
769         }
770 }
771
772 void
773 FaderPort::Button::set_action (string const& name, bool when_pressed, FaderPort::ButtonState bs)
774 {
775         ToDo todo;
776
777         todo.type = NamedAction;
778
779         if (when_pressed) {
780                 if (name.empty()) {
781                         on_press.erase (bs);
782                 } else {
783                         todo.action_name = name;
784                         on_press[bs] = todo;
785                 }
786         } else {
787                 if (name.empty()) {
788                         on_release.erase (bs);
789                 } else {
790                         todo.action_name = name;
791                         on_release[bs] = todo;
792                 }
793         }
794 }
795
796 string
797 FaderPort::Button::get_action (bool press, FaderPort::ButtonState bs)
798 {
799         ToDoMap::iterator x;
800
801         if (press) {
802                 if ((x = on_press.find (bs)) == on_press.end()) {
803                         return string();
804                 }
805                 if (x->second.type != NamedAction) {
806                         return string ();
807                 }
808                 return x->second.action_name;
809         } else {
810                 if ((x = on_release.find (bs)) == on_release.end()) {
811                         return string();
812                 }
813                 if (x->second.type != NamedAction) {
814                         return string ();
815                 }
816                 return x->second.action_name;
817         }
818 }
819
820 void
821 FaderPort::Button::set_action (boost::function<void()> f, bool when_pressed, FaderPort::ButtonState bs)
822 {
823         ToDo todo;
824         todo.type = InternalFunction;
825
826         if (when_pressed) {
827                 todo.function = f;
828                 on_press[bs] = todo;
829         } else {
830                 todo.function = f;
831                 on_release[bs] = todo;
832         }
833 }
834
835 void
836 FaderPort::Button::set_led_state (boost::shared_ptr<MIDI::Port> port, int onoff, bool force)
837 {
838         if (!force && (led_on == (bool) onoff)) {
839                 /* nothing to do */
840                 return;
841         }
842
843         if (out < 0) {
844                 /* fader button ID - no LED */
845                 return;
846         }
847
848         MIDI::byte buf[3];
849         buf[0] = 0xa0;
850         buf[1] = out;
851         buf[2] = onoff ? 1 : 0;
852         port->write (buf, 3, 0);
853         led_on = (onoff ? true : false);
854 }
855
856 int
857 FaderPort::Button::set_state (XMLNode const& node)
858 {
859         const XMLProperty* prop = node.property ("id");
860         if (!prop) {
861                 return -1;
862         }
863
864         int xid = atoi (prop->value());
865         if (xid != id) {
866                 return -1;
867         }
868
869         typedef pair<string,FaderPort::ButtonState> state_pair_t;
870         vector<state_pair_t> state_pairs;
871
872         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
873         state_pairs.push_back (make_pair (string ("shift"), ShiftDown));
874         state_pairs.push_back (make_pair (string ("longish"), LongishPress));
875         state_pairs.push_back (make_pair (string ("long"), LongPress));
876
877         on_press.clear ();
878         on_release.clear ();
879
880         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
881                 string propname;
882
883                 propname = sp->first + X_("-press");
884                 if ((prop = node.property (propname)) == 0) {
885                         continue;
886                 }
887                 set_action (prop->value(), true, sp->second);
888
889                 propname = sp->first + X_("-release");
890                 if ((prop = node.property (propname)) == 0) {
891                         continue;
892                 }
893                 set_action (prop->value(), false, sp->second);
894         }
895
896         return 0;
897 }
898
899 XMLNode&
900 FaderPort::Button::get_state () const
901 {
902         XMLNode* node = new XMLNode (X_("Button"));
903         char buf[16];
904         snprintf (buf, sizeof (buf), "%d", id);
905
906         node->add_property (X_("id"), buf);
907
908         ToDoMap::const_iterator x;
909         ToDo null;
910         null.type = NamedAction;
911
912         typedef pair<string,FaderPort::ButtonState> state_pair_t;
913         vector<state_pair_t> state_pairs;
914
915         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
916         state_pairs.push_back (make_pair (string ("shift"), ShiftDown));
917         state_pairs.push_back (make_pair (string ("longish"), LongishPress));
918         state_pairs.push_back (make_pair (string ("long"), LongPress));
919
920         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
921                 if ((x = on_press.find (sp->second)) != on_press.end()) {
922                         if (x->second.type == NamedAction) {
923                                 node->add_property (string (sp->first + X_("-press")).c_str(), x->second.action_name);
924                         }
925                 }
926
927                 if ((x = on_release.find (sp->second)) != on_release.end()) {
928                         if (x->second.type == NamedAction) {
929                                 node->add_property (string (sp->first + X_("-release")).c_str(), x->second.action_name);
930                         }
931                 }
932         }
933
934         return *node;
935 }
936
937 void
938 FaderPort::gui_track_selection_changed (RouteNotificationListPtr routes)
939 {
940         boost::shared_ptr<Route> r;
941
942         if (!routes->empty()) {
943                 r = routes->front().lock();
944         }
945
946         set_current_route (r);
947 }
948
949 void
950 FaderPort::drop_current_route ()
951 {
952         if (_current_route) {
953                 if (_current_route == session->monitor_out()) {
954                         set_current_route (session->master_out());
955                 } else {
956                         set_current_route (boost::shared_ptr<Route>());
957                 }
958         }
959 }
960
961 void
962 FaderPort::set_current_route (boost::shared_ptr<Route> r)
963 {
964         route_connections.drop_connections ();
965
966         _current_route = r;
967
968         /* turn this off. It will be turned on back on in use_master() or
969            use_monitor() as appropriate.
970         */
971         get_button(Output).set_led_state (_output_port, false);
972
973         if (_current_route) {
974                 _current_route->DropReferences.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::drop_current_route, this), this);
975
976                 _current_route->mute_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_mute, this, _1), this);
977                 _current_route->solo_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_solo, this, _1, _2, _3), this);
978                 _current_route->listen_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_listen, this, _1, _2), this);
979
980                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_route);
981                 if (t) {
982                         t->RecordEnableChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_recenable, this), this);
983                 }
984
985                 boost::shared_ptr<AutomationControl> control = _current_route->gain_control ();
986                 if (control) {
987                         control->Changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_gain, this), this);
988                 }
989
990                 boost::shared_ptr<MonitorProcessor> mp = _current_route->monitor_control();
991                 if (mp) {
992                         mp->cut_control()->Changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_cut, this), this);
993                 }
994         }
995
996         //ToDo: subscribe to the fader automation modes so we can light the LEDs
997
998         map_route_state ();
999 }
1000
1001 void
1002 FaderPort::map_cut ()
1003 {
1004         boost::shared_ptr<MonitorProcessor> mp = _current_route->monitor_control();
1005
1006         if (mp) {
1007                 bool yn = mp->cut_all ();
1008                 get_button (Mute).set_led_state (_output_port, yn);
1009                 if (yn) {
1010                         blinkers.push_back (Mute);
1011                 } else {
1012                         blinkers.remove (Mute);
1013                 }
1014         } else {
1015                 blinkers.remove (Mute);
1016         }
1017 }
1018
1019 void
1020 FaderPort::map_mute (void*)
1021 {
1022         get_button (Mute).set_led_state (_output_port, _current_route->muted());
1023 }
1024
1025 void
1026 FaderPort::map_solo (bool, void*, bool)
1027 {
1028         get_button (Solo).set_led_state (_output_port, _current_route->soloed() || _current_route->listening_via_monitor());
1029 }
1030
1031 void
1032 FaderPort::map_listen (void*, bool)
1033 {
1034         get_button (Solo).set_led_state (_output_port, _current_route->listening_via_monitor());
1035 }
1036
1037 void
1038 FaderPort::map_recenable ()
1039 {
1040         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_route);
1041         if (t) {
1042                 get_button (Rec).set_led_state (_output_port, t->record_enabled());
1043         } else {
1044                 get_button (Rec).set_led_state (_output_port, false);
1045         }
1046 }
1047
1048 void
1049 FaderPort::map_gain ()
1050 {
1051         if (fader_is_touched) {
1052                 /* Do not send fader moves while the user is touching the fader */
1053                 return;
1054         }
1055
1056         if (!_current_route) {
1057                 return;
1058         }
1059
1060         boost::shared_ptr<AutomationControl> control = _current_route->gain_control ();
1061         double val;
1062
1063         if (!control) {
1064                 val = 0.0;
1065         } else {
1066                 val = control->internal_to_interface (control->get_value ());
1067         }
1068
1069         /* Faderport sends fader position with range 0..16384 (though some of
1070          * the least-significant bits at the top end are missing - it may only
1071          * get to 1636X or so).
1072          *
1073          * But ... position must be sent in the range 0..1023.
1074          *
1075          * Thanks, Obama.
1076          */
1077
1078         int ival = (int) lrintf (val * 1023.0);
1079
1080         /* MIDI normalization requires that we send two separate messages here,
1081          * not one single 6 byte one.
1082          */
1083
1084         MIDI::byte buf[3];
1085
1086         buf[0] = 0xb0;
1087         buf[1] = 0x0;
1088         buf[2] = ival >> 7;
1089
1090         _output_port->write (buf, 3, 0);
1091
1092         buf[1] = 0x20;
1093         buf[2] = ival & 0x7f;
1094
1095         _output_port->write (buf, 3, 0);
1096 }
1097
1098 void
1099 FaderPort::map_route_state ()
1100 {
1101         if (!_current_route) {
1102                 get_button (Mute).set_led_state (_output_port, false);
1103                 get_button (Solo).set_led_state (_output_port, false);
1104                 get_button (Rec).set_led_state (_output_port, false);
1105                 blinkers.remove (Mute);
1106                 blinkers.remove (Solo);
1107         } else {
1108                 /* arguments to these map_*() methods are all ignored */
1109                 map_mute (0);
1110                 map_solo (false, 0, false);
1111                 map_recenable ();
1112                 map_gain ();
1113                 map_cut ();
1114         }
1115 }
1116
1117 boost::shared_ptr<Port>
1118 FaderPort::output_port()
1119 {
1120         return _output_port;
1121 }
1122
1123 boost::shared_ptr<Port>
1124 FaderPort::input_port()
1125 {
1126         return _input_port;
1127 }
1128
1129 void
1130 FaderPort::set_action (ButtonID id, std::string const& action_name, bool on_press, ButtonState bs)
1131 {
1132         get_button(id).set_action (action_name, on_press, bs);
1133 }
1134
1135 string
1136 FaderPort::get_action (ButtonID id, bool press, ButtonState bs)
1137 {
1138         return get_button(id).get_action (press, bs);
1139 }