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