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