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