faderport: generalized blink on/off code
[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                 /* set this bit on press, do NOT clear it on release */
317                 if (tb->value) {
318                         bs = ShiftDown;
319                 }
320                 break;
321         case Stop:
322                 bs = StopDown;
323                 break;
324         case Rewind:
325                 bs = RewindDown;
326                 break;
327         case User:
328                 bs = UserDown;
329                 break;
330         case FaderTouch:
331                 fader_is_touched = tb->value;
332                 if (_current_route) {
333                         boost::shared_ptr<AutomationControl> gain = _current_route->gain_control ();
334                         if (gain) {
335                                 framepos_t now = session->engine().sample_time();
336                                 if (tb->value) {
337                                         gain->start_touch (now);
338                                 } else {
339                                         gain->stop_touch (true, now);
340                                 }
341                         }
342                 }
343                 break;
344         default:
345                 if (tb->value) {
346                         start_press_timeout (button, id);
347                 }
348                 break;
349         }
350
351         if (bs) {
352                 button_state = (tb->value ? ButtonState (button_state|bs) : ButtonState (button_state&~bs));
353                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("reset button state to %1%2 using %3%4\n", hex, button_state, bs, dec));
354         }
355
356         if (button.uses_flash()) {
357                 button.set_led_state (_output_port, (int)tb->value);
358         }
359
360         button.invoke (button_state, tb->value ? true : false);
361
362         if (!tb->value && (id != Shift)) {
363                 /* non-shift key was released, clear shift modifier */
364                 button_state = ButtonState (button_state&~ShiftDown);
365                 DEBUG_TRACE (DEBUG::FaderPort, "clear shift modifier\n");
366         }
367 }
368
369 void
370 FaderPort::encoder_handler (MIDI::Parser &, MIDI::pitchbend_t pb)
371 {
372         int delta = 1;
373
374         if (pb >= 8192) {
375                 delta = -1;
376         }
377
378         //knob debouncing and hysteresis.  The presonus encoder often sends bursts of events, or goes the wrong direction
379         {
380                 last_last_encoder_delta = last_encoder_delta;
381                 last_encoder_delta = delta;
382                 microseconds_t now = get_microseconds ();
383                 if ((now - last_encoder_time) < 10*1000) { //require at least 10ms interval between changes, because the device sometimes sends multiple deltas
384                         return;
385                 }
386                 if ((now - last_encoder_time) < 100*1000) { //avoid directional changes while "spinning", 100ms window
387                         if ( (delta == last_encoder_delta) && (delta == last_last_encoder_delta) ) {
388                                 last_good_encoder_delta = delta;  //3 in a row, grudgingly accept this as the new direction
389                         }
390                         if (delta != last_good_encoder_delta) {  //otherwise ensure we keep going the same way
391                                 delta = last_good_encoder_delta;
392                         }
393                 } else {  //we aren't yet in a spin window, just assume this move is really what we want
394                         //NOTE:  if you are worried about where these get initialized, here it is.
395                         last_last_encoder_delta = delta;
396                         last_encoder_delta = delta;
397                 }
398                 last_encoder_time = now;
399                 last_good_encoder_delta = delta;
400         }
401
402         if (_current_route) {
403
404                 ButtonState trim_modifier;
405                 ButtonState width_modifier;
406
407                 if (Profile->get_mixbus()) {
408                         trim_modifier = ShiftDown;
409                         width_modifier = ButtonState (0);
410                 } else {
411                         trim_modifier = UserDown;
412                         width_modifier = ShiftDown;
413                 }
414
415                 if ((button_state & trim_modifier) == trim_modifier ) {    // mod+encoder = input trim
416                         boost::shared_ptr<AutomationControl> gain = _current_route->trim()->gain_control ();
417                         if (gain) {
418                                 float val = gain->get_user();  //for gain elements, the "user" value is in dB
419                                 val += delta;
420                                 gain->set_user(val);
421                         }
422                 } else if (width_modifier && ((button_state & width_modifier) == width_modifier)) {
423                         ardour_pan_width (delta);
424
425                 } else {  // pan/balance
426                         if (!Profile->get_mixbus()) {
427                                 ardour_pan_azimuth (delta);
428                         } else {
429                                 mixbus_pan (delta);
430                         }
431                 }
432         }
433 }
434
435 void
436 FaderPort::fader_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
437 {
438         bool was_fader = false;
439
440         if (tb->controller_number == 0x0) {
441                 fader_msb = tb->value;
442                 was_fader = true;
443         } else if (tb->controller_number == 0x20) {
444                 fader_lsb = tb->value;
445                 was_fader = true;
446         }
447
448         if (was_fader) {
449                 if (_current_route) {
450                         boost::shared_ptr<AutomationControl> gain = _current_route->gain_control ();
451                         if (gain) {
452                                 int ival = (fader_msb << 7) | fader_lsb;
453                                 float val = gain->interface_to_internal (ival/16384.0);
454                                 _current_route->set_gain (val, this);
455                         }
456                 }
457         }
458 }
459
460 void
461 FaderPort::sysex_handler (MIDI::Parser &p, MIDI::byte *buf, size_t sz)
462 {
463         if (sz < 17) {
464                 return;
465         }
466
467         if (buf[2] != 0x7f ||
468             buf[3] != 0x06 ||
469             buf[4] != 0x02 ||
470             buf[5] != 0x0 ||
471             buf[6] != 0x1 ||
472             buf[7] != 0x06 ||
473             buf[8] != 0x02 ||
474             buf[9] != 0x0 ||
475             buf[10] != 0x01 ||
476             buf[11] != 0x0) {
477                 return;
478         }
479
480         _device_active = true;
481
482         DEBUG_TRACE (DEBUG::FaderPort, "FaderPort identified via MIDI Device Inquiry response\n");
483
484         /* put it into native mode */
485
486         MIDI::byte native[3];
487         native[0] = 0x91;
488         native[1] = 0x00;
489         native[2] = 0x64;
490
491         _output_port->write (native, 3, 0);
492
493         all_lights_out ();
494
495         /* catch up on state */
496
497         notify_transport_state_changed ();
498         notify_record_state_changed ();
499 }
500
501 int
502 FaderPort::set_active (bool yn)
503 {
504         DEBUG_TRACE (DEBUG::FaderPort, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
505
506         if (yn == active()) {
507                 return 0;
508         }
509
510         if (yn) {
511
512                 /* start event loop */
513
514                 BaseUI::run ();
515
516                 connect_session_signals ();
517
518                 Glib::RefPtr<Glib::TimeoutSource> blink_timeout = Glib::TimeoutSource::create (200); // milliseconds
519                 blink_connection = blink_timeout->connect (sigc::mem_fun (*this, &FaderPort::blink));
520                 blink_timeout->attach (main_loop()->get_context());
521
522         } else {
523
524                 BaseUI::quit ();
525                 close ();
526
527         }
528
529         ControlProtocol::set_active (yn);
530
531         DEBUG_TRACE (DEBUG::FaderPort, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
532
533         return 0;
534 }
535
536 void
537 FaderPort::stop_blinking (ButtonID id)
538 {
539         blinkers.remove (id);
540         get_button (id).set_led_state (_output_port, false);
541 }
542
543 void
544 FaderPort::start_blinking (ButtonID id)
545 {
546         blinkers.push_back (id);
547         get_button (id).set_led_state (_output_port, true);
548 }
549
550 bool
551 FaderPort::blink ()
552 {
553         blink_state = !blink_state;
554
555         for (Blinkers::iterator b = blinkers.begin(); b != blinkers.end(); b++) {
556                 get_button(*b).set_led_state (_output_port, blink_state);
557         }
558
559         return true;
560 }
561
562 void
563 FaderPort::close ()
564 {
565         all_lights_out ();
566
567         stop_midi_handling ();
568         session_connections.drop_connections ();
569         port_connection.disconnect ();
570         blink_connection.disconnect ();
571         selection_connection.disconnect ();
572         route_connections.drop_connections ();
573
574 #if 0
575         route_connections.drop_connections ();
576 #endif
577 }
578
579 void
580 FaderPort::notify_record_state_changed ()
581 {
582         switch (session->record_status()) {
583         case Session::Disabled:
584                 stop_blinking (RecEnable);
585                 break;
586         case Session::Enabled:
587                 start_blinking (RecEnable);
588                 break;
589         case Session::Recording:
590                 stop_blinking (RecEnable);
591                 break;
592         }
593 }
594
595 void
596 FaderPort::notify_transport_state_changed ()
597 {
598         get_button (Loop).set_led_state (_output_port, session->get_play_loop());
599         get_button (Play).set_led_state (_output_port, session->transport_speed() == 1.0);
600         get_button (Stop).set_led_state (_output_port, session->transport_stopped ());
601         get_button (Rewind).set_led_state (_output_port, session->transport_speed() < 0.0);
602         get_button (Ffwd).set_led_state (_output_port, session->transport_speed() > 1.0);
603 }
604
605 void
606 FaderPort::parameter_changed (string what)
607 {
608         if (what == "punch-in" || what == "punch-out") {
609                 bool in = session->config.get_punch_in ();
610                 bool out = session->config.get_punch_out ();
611                 if (in && out) {
612                         get_button (Punch).set_led_state (_output_port, true);
613                         blinkers.remove (Punch);
614                 } else if (in || out) {
615                         start_blinking (Punch);
616                 } else {
617                         stop_blinking (Punch);
618                 }
619         }
620 }
621
622 void
623 FaderPort::connect_session_signals()
624 {
625         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::notify_record_state_changed, this), this);
626         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::notify_transport_state_changed, this), this);
627         /* not session, but treat it similarly */
628         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::parameter_changed, this, _1), this);
629 }
630
631 bool
632 FaderPort::midi_input_handler (Glib::IOCondition ioc, boost::shared_ptr<ARDOUR::AsyncMIDIPort> port)
633 {
634         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("something happend on  %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
635
636         if (ioc & ~IO_IN) {
637                 return false;
638         }
639
640         if (ioc & IO_IN) {
641
642                 if (port) {
643                         port->clear ();
644                 }
645
646                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("data available on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
647                 framepos_t now = session->engine().sample_time();
648                 port->parse (now);
649         }
650
651         return true;
652 }
653
654
655 XMLNode&
656 FaderPort::get_state ()
657 {
658         XMLNode& node (ControlProtocol::get_state());
659
660         XMLNode* child;
661
662         child = new XMLNode (X_("Input"));
663         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_input_port)->get_state());
664         node.add_child_nocopy (*child);
665
666
667         child = new XMLNode (X_("Output"));
668         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_output_port)->get_state());
669         node.add_child_nocopy (*child);
670
671         /* Save action state for Mix, Proj, Trns and User buttons, since these
672          * are user controlled. We can only save named-action operations, since
673          * internal functions are just pointers to functions and hard to
674          * serialize without enumerating them all somewhere.
675          */
676
677         node.add_child_nocopy (get_button (Mix).get_state());
678         node.add_child_nocopy (get_button (Proj).get_state());
679         node.add_child_nocopy (get_button (Trns).get_state());
680         node.add_child_nocopy (get_button (User).get_state());
681
682         return node;
683 }
684
685 int
686 FaderPort::set_state (const XMLNode& node, int version)
687 {
688         XMLNodeList nlist;
689         XMLNodeConstIterator niter;
690         XMLNode const* child;
691
692         if (ControlProtocol::set_state (node, version)) {
693                 return -1;
694         }
695
696         if ((child = node.child (X_("Input"))) != 0) {
697                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
698                 if (portnode) {
699                         boost::shared_ptr<ARDOUR::Port>(_input_port)->set_state (*portnode, version);
700                 }
701         }
702
703         if ((child = node.child (X_("Output"))) != 0) {
704                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
705                 if (portnode) {
706                         boost::shared_ptr<ARDOUR::Port>(_output_port)->set_state (*portnode, version);
707                 }
708         }
709
710         for (XMLNodeList::const_iterator n = node.children().begin(); n != node.children().end(); ++n) {
711                 if ((*n)->name() == X_("Button")) {
712                         XMLProperty const * prop = (*n)->property (X_("id"));
713                         if (!prop) {
714                                 continue;
715                         }
716                         int xid = atoi (prop->value());
717                         ButtonMap::iterator b = buttons.find (ButtonID (xid));
718                         if (b == buttons.end()) {
719                                 continue;
720                         }
721                         b->second.set_state (**n);
722                 }
723         }
724
725         return 0;
726 }
727
728 bool
729 FaderPort::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
730 {
731         if (!_input_port || !_output_port) {
732                 return false;
733         }
734
735         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
736         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
737
738         if (ni == name1 || ni == name2) {
739                 if (yn) {
740                         connection_state |= InputConnected;
741                 } else {
742                         connection_state &= ~InputConnected;
743                 }
744         } else if (no == name1 || no == name2) {
745                 if (yn) {
746                         connection_state |= OutputConnected;
747                 } else {
748                         connection_state &= ~OutputConnected;
749                 }
750         } else {
751                 /* not our ports */
752                 return false;
753         }
754
755         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
756
757                 /* XXX this is a horrible hack. Without a short sleep here,
758                    something prevents the device wakeup messages from being
759                    sent and/or the responses from being received.
760                 */
761
762                 g_usleep (100000);
763                 connected ();
764
765         } else {
766                 DEBUG_TRACE (DEBUG::FaderPort, "Device disconnected (input or output or both) or not yet fully connected\n");
767                 _device_active = false;
768         }
769
770         ConnectionChange (); /* emit signal for our GUI */
771
772         return true; /* connection status changed */
773 }
774
775 void
776 FaderPort::connected ()
777 {
778         DEBUG_TRACE (DEBUG::FaderPort, "connection status changed\n");
779
780         start_midi_handling ();
781
782         /* send device inquiry */
783
784         MIDI::byte buf[6];
785
786         buf[0] = 0xf0;
787         buf[1] = 0x7e;
788         buf[2] = 0x7f;
789         buf[3] = 0x06;
790         buf[4] = 0x01;
791         buf[5] = 0xf7;
792
793         _output_port->write (buf, 6, 0);
794 }
795
796 void
797 FaderPort::Button::invoke (FaderPort::ButtonState bs, bool press)
798 {
799         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("invoke button %1 for %2 state %3%4%5\n", id, (press ? "press":"release"), hex, bs, dec));
800
801         ToDoMap::iterator x;
802
803         if (press) {
804                 if ((x = on_press.find (bs)) == on_press.end()) {
805                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("no press action for button %1 state %2%3\%4\n", id, hex, bs, dec));
806                         return;
807                 }
808         } else {
809                 if ((x = on_release.find (bs)) == on_release.end()) {
810                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("no release action for button %1 state %2%3\%4\n", id, hex, bs, dec));
811                         return;
812                 }
813         }
814
815         switch (x->second.type) {
816         case NamedAction:
817                 if (!x->second.action_name.empty()) {
818                         fp.access_action (x->second.action_name);
819                 }
820                 break;
821         case InternalFunction:
822                 if (x->second.function) {
823                         x->second.function ();
824                 }
825         }
826 }
827
828 void
829 FaderPort::Button::set_action (string const& name, bool when_pressed, FaderPort::ButtonState bs)
830 {
831         ToDo todo;
832
833         todo.type = NamedAction;
834
835         if (when_pressed) {
836                 if (name.empty()) {
837                         on_press.erase (bs);
838                 } else {
839                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("set button %1 to action %2 on press + %3%4%5\n", id, name, bs));
840                         todo.action_name = name;
841                         on_press[bs] = todo;
842                 }
843         } else {
844                 if (name.empty()) {
845                         on_release.erase (bs);
846                 } else {
847                         DEBUG_TRACE (DEBUG::FaderPort, string_compose ("set button %1 to action %2 on release + %3%4%5\n", id, name, bs));
848                         todo.action_name = name;
849                         on_release[bs] = todo;
850                 }
851         }
852 }
853
854 string
855 FaderPort::Button::get_action (bool press, FaderPort::ButtonState bs)
856 {
857         ToDoMap::iterator x;
858
859         if (press) {
860                 if ((x = on_press.find (bs)) == on_press.end()) {
861                         return string();
862                 }
863                 if (x->second.type != NamedAction) {
864                         return string ();
865                 }
866                 return x->second.action_name;
867         } else {
868                 if ((x = on_release.find (bs)) == on_release.end()) {
869                         return string();
870                 }
871                 if (x->second.type != NamedAction) {
872                         return string ();
873                 }
874                 return x->second.action_name;
875         }
876 }
877
878 void
879 FaderPort::Button::set_action (boost::function<void()> f, bool when_pressed, FaderPort::ButtonState bs)
880 {
881         ToDo todo;
882         todo.type = InternalFunction;
883
884         if (when_pressed) {
885                 todo.function = f;
886                 on_press[bs] = todo;
887         } else {
888                 todo.function = f;
889                 on_release[bs] = todo;
890         }
891 }
892
893 void
894 FaderPort::Button::set_led_state (boost::shared_ptr<MIDI::Port> port, int onoff, bool force)
895 {
896         if (!force && (led_on == (bool) onoff)) {
897                 /* nothing to do */
898                 return;
899         }
900
901         if (out < 0) {
902                 /* fader button ID - no LED */
903                 return;
904         }
905
906         MIDI::byte buf[3];
907         buf[0] = 0xa0;
908         buf[1] = out;
909         buf[2] = onoff ? 1 : 0;
910         port->write (buf, 3, 0);
911         led_on = (onoff ? true : false);
912 }
913
914 int
915 FaderPort::Button::set_state (XMLNode const& node)
916 {
917         const XMLProperty* prop = node.property ("id");
918         if (!prop) {
919                 return -1;
920         }
921
922         int xid = atoi (prop->value());
923         if (xid != id) {
924                 return -1;
925         }
926
927         typedef pair<string,FaderPort::ButtonState> state_pair_t;
928         vector<state_pair_t> state_pairs;
929
930         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
931         state_pairs.push_back (make_pair (string ("shift"), ShiftDown));
932         state_pairs.push_back (make_pair (string ("long"), LongPress));
933
934         on_press.clear ();
935         on_release.clear ();
936
937         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
938                 string propname;
939
940                 propname = sp->first + X_("-press");
941                 if ((prop = node.property (propname)) != 0) {
942                         set_action (prop->value(), true, sp->second);
943                 }
944
945                 propname = sp->first + X_("-release");
946                 if ((prop = node.property (propname)) != 0) {
947                         set_action (prop->value(), false, sp->second);
948                 }
949         }
950
951         return 0;
952 }
953
954 XMLNode&
955 FaderPort::Button::get_state () const
956 {
957         XMLNode* node = new XMLNode (X_("Button"));
958         char buf[16];
959         snprintf (buf, sizeof (buf), "%d", id);
960
961         node->add_property (X_("id"), buf);
962
963         ToDoMap::const_iterator x;
964         ToDo null;
965         null.type = NamedAction;
966
967         typedef pair<string,FaderPort::ButtonState> state_pair_t;
968         vector<state_pair_t> state_pairs;
969
970         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
971         state_pairs.push_back (make_pair (string ("shift"), ShiftDown));
972         state_pairs.push_back (make_pair (string ("long"), LongPress));
973
974         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
975                 if ((x = on_press.find (sp->second)) != on_press.end()) {
976                         if (x->second.type == NamedAction) {
977                                 node->add_property (string (sp->first + X_("-press")).c_str(), x->second.action_name);
978                         }
979                 }
980
981                 if ((x = on_release.find (sp->second)) != on_release.end()) {
982                         if (x->second.type == NamedAction) {
983                                 node->add_property (string (sp->first + X_("-release")).c_str(), x->second.action_name);
984                         }
985                 }
986         }
987
988         return *node;
989 }
990
991 void
992 FaderPort::gui_track_selection_changed (RouteNotificationListPtr routes)
993 {
994         boost::shared_ptr<Route> r;
995
996         if (!routes->empty()) {
997                 r = routes->front().lock();
998         }
999
1000         set_current_route (r);
1001 }
1002
1003 void
1004 FaderPort::drop_current_route ()
1005 {
1006         if (_current_route) {
1007                 if (_current_route == session->monitor_out()) {
1008                         set_current_route (session->master_out());
1009                 } else {
1010                         set_current_route (boost::shared_ptr<Route>());
1011                 }
1012         }
1013 }
1014
1015 void
1016 FaderPort::set_current_route (boost::shared_ptr<Route> r)
1017 {
1018         route_connections.drop_connections ();
1019
1020         _current_route = r;
1021
1022         /* turn this off. It will be turned on back on in use_master() or
1023            use_monitor() as appropriate.
1024         */
1025         get_button(Output).set_led_state (_output_port, false);
1026
1027         if (_current_route) {
1028                 _current_route->DropReferences.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::drop_current_route, this), this);
1029
1030                 _current_route->mute_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_mute, this, _1), this);
1031                 _current_route->solo_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_solo, this, _1, _2, _3), this);
1032                 _current_route->listen_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_listen, this, _1, _2), this);
1033
1034                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_route);
1035                 if (t) {
1036                         t->RecordEnableChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_recenable, this), this);
1037                 }
1038
1039                 boost::shared_ptr<AutomationControl> control = _current_route->gain_control ();
1040                 if (control) {
1041                         control->Changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_gain, this), this);
1042                         control->alist()->automation_state_changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_auto, this), this);
1043                 }
1044
1045                 boost::shared_ptr<MonitorProcessor> mp = _current_route->monitor_control();
1046                 if (mp) {
1047                         mp->cut_control()->Changed.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort::map_cut, this), this);
1048                 }
1049         }
1050
1051         //ToDo: subscribe to the fader automation modes so we can light the LEDs
1052
1053         map_route_state ();
1054 }
1055
1056 void
1057 FaderPort::map_auto ()
1058 {
1059         boost::shared_ptr<AutomationControl> control = _current_route->gain_control ();
1060         const AutoState as = control->automation_state ();
1061
1062         switch (as) {
1063                 case ARDOUR::Play:
1064                         get_button (FP_Read).set_led_state (_output_port, true);
1065                         get_button (FP_Write).set_led_state (_output_port, false);
1066                         get_button (FP_Touch).set_led_state (_output_port, false);
1067                         get_button (FP_Off).set_led_state (_output_port, false);
1068                 break;
1069                 case ARDOUR::Write:
1070                         get_button (FP_Read).set_led_state (_output_port, false);
1071                         get_button (FP_Write).set_led_state (_output_port, true);
1072                         get_button (FP_Touch).set_led_state (_output_port, false);
1073                         get_button (FP_Off).set_led_state (_output_port, false);
1074                 break;
1075                 case ARDOUR::Touch:
1076                         get_button (FP_Read).set_led_state (_output_port, false);
1077                         get_button (FP_Write).set_led_state (_output_port, false);
1078                         get_button (FP_Touch).set_led_state (_output_port, true);
1079                         get_button (FP_Off).set_led_state (_output_port, false);
1080                 break;
1081                 case ARDOUR::Off:
1082                         get_button (FP_Read).set_led_state (_output_port, false);
1083                         get_button (FP_Write).set_led_state (_output_port, false);
1084                         get_button (FP_Touch).set_led_state (_output_port, false);
1085                         get_button (FP_Off).set_led_state (_output_port, true);
1086                 break;
1087         }
1088         
1089 }
1090
1091
1092 void
1093 FaderPort::map_cut ()
1094 {
1095         boost::shared_ptr<MonitorProcessor> mp = _current_route->monitor_control();
1096
1097         if (mp) {
1098                 bool yn = mp->cut_all ();
1099                 if (yn) {
1100                         start_blinking (Mute);
1101                 } else {
1102                         stop_blinking (Mute);
1103                 }
1104         } else {
1105                 stop_blinking (Mute);
1106         }
1107 }
1108
1109 void
1110 FaderPort::map_mute (void*)
1111 {
1112         get_button (Mute).set_led_state (_output_port, _current_route->muted());
1113 }
1114
1115 void
1116 FaderPort::map_solo (bool, void*, bool)
1117 {
1118         get_button (Solo).set_led_state (_output_port, _current_route->soloed() || _current_route->listening_via_monitor());
1119 }
1120
1121 void
1122 FaderPort::map_listen (void*, bool)
1123 {
1124         get_button (Solo).set_led_state (_output_port, _current_route->listening_via_monitor());
1125 }
1126
1127 void
1128 FaderPort::map_recenable ()
1129 {
1130         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_route);
1131         if (t) {
1132                 get_button (Rec).set_led_state (_output_port, t->record_enabled());
1133         } else {
1134                 get_button (Rec).set_led_state (_output_port, false);
1135         }
1136 }
1137
1138 void
1139 FaderPort::map_gain ()
1140 {
1141         if (fader_is_touched) {
1142                 /* Do not send fader moves while the user is touching the fader */
1143                 return;
1144         }
1145
1146         if (!_current_route) {
1147                 return;
1148         }
1149
1150         boost::shared_ptr<AutomationControl> control = _current_route->gain_control ();
1151         double val;
1152
1153         if (!control) {
1154                 val = 0.0;
1155         } else {
1156                 val = control->internal_to_interface (control->get_value ());
1157         }
1158
1159         /* Faderport sends fader position with range 0..16384 (though some of
1160          * the least-significant bits at the top end are missing - it may only
1161          * get to 1636X or so).
1162          *
1163          * But ... position must be sent in the range 0..1023.
1164          *
1165          * Thanks, Obama.
1166          */
1167
1168         int ival = (int) lrintf (val * 1023.0);
1169
1170         /* MIDI normalization requires that we send two separate messages here,
1171          * not one single 6 byte one.
1172          */
1173
1174         MIDI::byte buf[3];
1175
1176         buf[0] = 0xb0;
1177         buf[1] = 0x0;
1178         buf[2] = ival >> 7;
1179
1180         _output_port->write (buf, 3, 0);
1181
1182         buf[1] = 0x20;
1183         buf[2] = ival & 0x7f;
1184
1185         _output_port->write (buf, 3, 0);
1186 }
1187
1188 void
1189 FaderPort::map_route_state ()
1190 {
1191         if (!_current_route) {
1192                 stop_blinking (Mute);
1193                 stop_blinking (Solo);
1194                 get_button (Rec).set_led_state (_output_port, false);
1195         } else {
1196                 /* arguments to these map_*() methods are all ignored */
1197                 map_mute (0);
1198                 map_solo (false, 0, false);
1199                 map_recenable ();
1200                 map_gain ();
1201                 map_cut ();
1202                 map_auto ();
1203         }
1204 }
1205
1206 boost::shared_ptr<Port>
1207 FaderPort::output_port()
1208 {
1209         return _output_port;
1210 }
1211
1212 boost::shared_ptr<Port>
1213 FaderPort::input_port()
1214 {
1215         return _input_port;
1216 }
1217
1218 void
1219 FaderPort::set_action (ButtonID id, std::string const& action_name, bool on_press, ButtonState bs)
1220 {
1221         get_button(id).set_action (action_name, on_press, bs);
1222 }
1223
1224 string
1225 FaderPort::get_action (ButtonID id, bool press, ButtonState bs)
1226 {
1227         return get_button(id).get_action (press, bs);
1228 }