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