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