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