Small improvement and change to comply with coding standard
[ardour.git] / libs / surfaces / cc121 / cc121.cc
1 /*
2     Copyright (C) 2015 Paul Davis
3     Copyright (C) 2016 W.P. van Paassen
4
5     Thanks to Rolf Meyerhoff for reverse engineering the CC121 protocol.
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program; if not, write to the Free Software
19     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 */
22
23 #include <cstdlib>
24 #include <sstream>
25 #include <algorithm>
26
27 #include <stdint.h>
28
29 #include <glibmm/fileutils.h>
30 #include <glibmm/miscutils.h>
31
32 #include "pbd/error.h"
33 #include "pbd/failed_constructor.h"
34 #include "pbd/file_utils.h"
35 #include "pbd/pthread_utils.h"
36 #include "pbd/compose.h"
37 #include "pbd/xml++.h"
38
39 #include "midi++/port.h"
40
41 #include "control_protocol/basic_ui.h"
42
43 #include "ardour/async_midi_port.h"
44 #include "ardour/audioengine.h"
45 #include "ardour/amp.h"
46 #include "ardour/bundle.h"
47 #include "ardour/controllable_descriptor.h"
48 #include "ardour/debug.h"
49 #include "ardour/filesystem_paths.h"
50 #include "ardour/midi_port.h"
51 #include "ardour/midiport_manager.h"
52 #include "ardour/monitor_processor.h"
53 #include "ardour/profile.h"
54 #include "ardour/rc_configuration.h"
55 #include "ardour/record_enable_control.h"
56 #include "ardour/stripable.h"
57 #include "ardour/session.h"
58 #include "ardour/session_configuration.h"
59 #include "ardour/track.h"
60
61 #include "cc121.h"
62
63 using namespace ARDOUR;
64 using namespace ArdourSurface;
65 using namespace PBD;
66 using namespace Glib;
67 using namespace std;
68
69 #include "pbd/i18n.h"
70
71 #include "pbd/abstract_ui.cc" // instantiate template
72
73 CC121::CC121 (Session& s)
74         : ControlProtocol (s, _("Steinberg CC121"))
75         , AbstractUI<CC121Request> (name())
76         , gui (0)
77         , connection_state (ConnectionState (0))
78         , _device_active (false)
79         , fader_msb (0)
80         , fader_lsb (0)
81         , fader_is_touched (false)
82         , _jogmode(scroll)
83         , button_state (ButtonState (0))
84         , blink_state (false)
85         , rec_enable_state (false)
86 {
87         last_encoder_time = 0;
88
89         boost::shared_ptr<ARDOUR::Port> inp;
90         boost::shared_ptr<ARDOUR::Port> outp;
91
92         inp  = AudioEngine::instance()->register_input_port (DataType::MIDI, "CC121 Recv", true);
93         outp = AudioEngine::instance()->register_output_port (DataType::MIDI, "CC121 Send", true);
94
95         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(inp);
96         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(outp);
97
98         if (_input_port == 0 || _output_port == 0) {
99                 throw failed_constructor();
100         }
101
102         _input_bundle.reset (new ARDOUR::Bundle (_("CC121 Support (Receive)"), true));
103         _output_bundle.reset (new ARDOUR::Bundle (_("CC121 Support (Send) "), false));
104
105         _input_bundle->add_channel (
106                 inp->name(),
107                 ARDOUR::DataType::MIDI,
108                 session->engine().make_port_name_non_relative (inp->name())
109                 );
110
111         _output_bundle->add_channel (
112                 outp->name(),
113                 ARDOUR::DataType::MIDI,
114                 session->engine().make_port_name_non_relative (outp->name())
115                 );
116
117
118         StripableSelectionChanged.connect (selection_connection, MISSING_INVALIDATOR, boost::bind (&CC121::gui_track_selection_changed, this, _1), this);
119
120         /* Catch port connections and disconnections */
121         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&CC121::connection_handler, this, _1, _2, _3, _4, _5), this);
122         buttons.insert (std::make_pair (EButton, Button (*this, _("EButton"), EButton)));
123         buttons.insert (std::make_pair (OpenVST, Button (*this, _("OpenVST"), OpenVST)));
124         buttons.insert (std::make_pair (InputMonitor, Button (*this, _("InputMonitor"), InputMonitor)));
125         buttons.insert (std::make_pair (EQ1Enable, Button (*this, _("EQ1Enable"), EQ1Enable)));
126         buttons.insert (std::make_pair (EQ2Enable, Button (*this, _("EQ2Enable"), EQ2Enable)));
127         buttons.insert (std::make_pair (EQ3Enable, Button (*this, _("EQ3Enable"), EQ3Enable)));
128         buttons.insert (std::make_pair (EQ4Enable, Button (*this, _("EQ4Enable"), EQ4Enable)));
129         buttons.insert (std::make_pair (EQType, Button (*this, _("EQType"), EQType)));
130         buttons.insert (std::make_pair (AllBypass, Button (*this, _("AllBypass"), AllBypass)));
131         buttons.insert (std::make_pair (Function1, Button (*this, _("Function1"), Function1)));
132         buttons.insert (std::make_pair (Function2, Button (*this, _("Function2"), Function2)));
133         buttons.insert (std::make_pair (Function3, Button (*this, _("Function3"), Function3)));
134         buttons.insert (std::make_pair (Function4, Button (*this, _("Function4"), Function4)));
135         buttons.insert (std::make_pair (Value, Button (*this, _("Value"), Value)));
136         buttons.insert (std::make_pair (Jog, Button (*this, _("Jog"), Jog)));
137         buttons.insert (std::make_pair (Lock, Button (*this, _("Lock"), Lock)));
138         buttons.insert (std::make_pair (ToStart, Button (*this, _("ToStart"), ToStart)));
139         buttons.insert (std::make_pair (ToEnd, Button (*this, _("ToEnd"), ToEnd)));
140         buttons.insert (std::make_pair (Mute, Button (*this, _("Mute"), Mute)));
141         buttons.insert (std::make_pair (Solo, Button (*this, _("Solo"), Solo)));
142         buttons.insert (std::make_pair (Rec, Button (*this, _("Rec"), Rec)));
143         buttons.insert (std::make_pair (Left, Button (*this, _("Left"), Left)));
144         buttons.insert (std::make_pair (Right, Button (*this, _("Right"), Right)));
145         buttons.insert (std::make_pair (Output, Button (*this, _("Output"), Output)));
146         buttons.insert (std::make_pair (FP_Read, Button (*this, _("Read"), FP_Read)));
147         buttons.insert (std::make_pair (FP_Write, Button (*this, _("Write"), FP_Write)));
148         buttons.insert (std::make_pair (Loop, Button (*this, _("Loop"), Loop)));
149         buttons.insert (std::make_pair (Rewind, Button (*this, _("Rewind"), Rewind)));
150         buttons.insert (std::make_pair (Ffwd, Button (*this, _("Ffwd"), Ffwd)));
151         buttons.insert (std::make_pair (Stop, Button (*this, _("Stop"), Stop)));
152         buttons.insert (std::make_pair (Play, Button (*this, _("Play"), Play)));
153         buttons.insert (std::make_pair (RecEnable, Button (*this, _("RecEnable"), RecEnable)));
154         buttons.insert (std::make_pair (Footswitch, Button (*this, _("Footswitch"), Footswitch)));
155         buttons.insert (std::make_pair (FaderTouch, Button (*this, _("Fader (touch)"), FaderTouch)));
156
157         get_button (Left).set_action ( boost::bind (&CC121::left, this), true);
158         get_button (Right).set_action ( boost::bind (&CC121::right, this), true);
159
160         get_button (FP_Read).set_action (boost::bind (&CC121::read, this), true);
161         get_button (FP_Write).set_action (boost::bind (&CC121::write, this), true);
162         get_button (EButton).set_action (boost::bind (&CC121::touch, this), true);
163         get_button (OpenVST).set_action (boost::bind (&CC121::off, this), true);
164
165         get_button (Play).set_action (boost::bind (&BasicUI::transport_play, this, true), true);
166         get_button (ToStart).set_action (boost::bind (&BasicUI::prev_marker, this), true);
167         get_button (ToEnd).set_action (boost::bind (&BasicUI::next_marker, this), true);
168         get_button (RecEnable).set_action (boost::bind (&BasicUI::rec_enable_toggle, this), true);
169         get_button (Stop).set_action (boost::bind (&BasicUI::transport_stop, this), true);
170         get_button (Ffwd).set_action (boost::bind (&BasicUI::ffwd, this), true);
171
172         get_button (Rewind).set_action (boost::bind (&BasicUI::rewind, this), true);
173         get_button (Loop).set_action (boost::bind (&BasicUI::loop_toggle, this), true);
174
175         get_button (Jog).set_action (boost::bind (&CC121::jog, this), true);
176         get_button (Mute).set_action (boost::bind (&CC121::mute, this), true);
177         get_button (Solo).set_action (boost::bind (&CC121::solo, this), true);
178         get_button (Rec).set_action (boost::bind (&CC121::rec_enable, this), true);
179
180         get_button (InputMonitor).set_action (boost::bind (&CC121::input_monitor, this), true);
181 }
182
183 CC121::~CC121 ()
184 {
185         all_lights_out ();
186
187         if (_input_port) {
188                 DEBUG_TRACE (DEBUG::CC121, string_compose ("unregistering input port %1\n", boost::shared_ptr<ARDOUR::Port>(_input_port)->name()));
189                 AudioEngine::instance()->unregister_port (_input_port);
190                 _input_port.reset ();
191         }
192
193         if (_output_port) {
194                 _output_port->drain (10000,  250000); /* check every 10 msecs, wait up to 1/4 second for the port to drain */
195                 DEBUG_TRACE (DEBUG::CC121, string_compose ("unregistering output port %1\n", boost::shared_ptr<ARDOUR::Port>(_output_port)->name()));
196                 AudioEngine::instance()->unregister_port (_output_port);
197                 _output_port.reset ();
198         }
199
200         tear_down_gui ();
201
202         /* stop event loop */
203         DEBUG_TRACE (DEBUG::CC121, "BaseUI::quit ()\n");
204         BaseUI::quit ();
205 }
206
207 void*
208 CC121::request_factory (uint32_t num_requests)
209 {
210         /* AbstractUI<T>::request_buffer_factory() is a template method only
211            instantiated in this source module. To provide something visible for
212            use in the interface/descriptor, we have this static method that is
213            template-free.
214         */
215         return request_buffer_factory (num_requests);
216 }
217
218 void
219 CC121::start_midi_handling ()
220 {
221         /* handle buttons press */
222         _input_port->parser()->channel_note_on[0].connect_same_thread (midi_connections, boost::bind (&CC121::button_press_handler, this, _1, _2));
223         /* handle buttons release*/
224         _input_port->parser()->channel_note_off[0].connect_same_thread (midi_connections, boost::bind (&CC121::button_release_handler, this, _1, _2));
225         /* handle fader */
226         _input_port->parser()->pitchbend.connect_same_thread (midi_connections, boost::bind (&CC121::fader_handler, this, _1, _2));
227         /* handle encoder */
228         _input_port->parser()->controller.connect_same_thread (midi_connections, boost::bind (&CC121::encoder_handler, this, _1, _2));
229
230         /* This connection means that whenever data is ready from the input
231          * port, the relevant thread will invoke our ::midi_input_handler()
232          * method, which will read the data, and invoke the parser.
233          */
234
235         _input_port->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &CC121::midi_input_handler), _input_port));
236         _input_port->xthread().attach (main_loop()->get_context());
237 }
238
239 void
240 CC121::stop_midi_handling ()
241 {
242         midi_connections.drop_connections ();
243
244         /* Note: the input handler is still active at this point, but we're no
245          * longer connected to any of the parser signals
246          */
247 }
248
249 void
250 CC121::do_request (CC121Request* req)
251 {
252         if (req->type == CallSlot) {
253
254                 call_slot (MISSING_INVALIDATOR, req->the_slot);
255
256         } else if (req->type == Quit) {
257
258                 stop ();
259         }
260 }
261
262 int
263 CC121::stop ()
264 {
265         BaseUI::quit ();
266
267         return 0;
268 }
269
270 void
271 CC121::thread_init ()
272 {
273         struct sched_param rtparam;
274
275         pthread_set_name (event_loop_name().c_str());
276
277         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
278         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
279
280         memset (&rtparam, 0, sizeof (rtparam));
281         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
282
283         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
284                 // do we care? not particularly.
285         }
286 }
287
288 void
289 CC121::all_lights_out ()
290 {
291         for (ButtonMap::iterator b = buttons.begin(); b != buttons.end(); ++b) {
292                 b->second.set_led_state (_output_port, false);
293         }
294 }
295
296 CC121::Button&
297 CC121::get_button (ButtonID id) const
298 {
299         ButtonMap::const_iterator b = buttons.find (id);
300         assert (b != buttons.end());
301         return const_cast<Button&>(b->second);
302 }
303
304 void
305 CC121::button_press_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
306 {
307         DEBUG_TRACE (DEBUG::CC121, string_compose ("button press event for ID %1 press ? %2\n", (int) tb->controller_number, (tb->value ? "yes" : "no")));
308
309         ButtonID id (ButtonID (tb->controller_number));
310         Button& button (get_button (id));
311
312         buttons_down.insert (id);
313         ButtonState bs (ButtonState (0));
314
315         switch (id) {
316         case FaderTouch:
317           fader_is_touched = true;
318                 if (_current_stripable) {
319                         boost::shared_ptr<AutomationControl> gain = _current_stripable->gain_control ();
320                         if (gain) {
321                           framepos_t now = session->engine().sample_time();
322                           gain->start_touch (now);
323                         }
324                 }
325                 break;
326         default:
327           break;
328         }
329
330         if (bs) {
331                 button_state = ButtonState (button_state|bs);
332                 DEBUG_TRACE (DEBUG::CC121, string_compose ("reset button state to %1 using %2\n", button_state, (int) bs));
333         }
334
335         if (button.uses_flash()) {
336                 button.set_led_state (_output_port, (int)tb->value);
337         }
338
339         set<ButtonID>::iterator c = consumed.find (id);
340
341         if (c == consumed.end()) {
342                 button.invoke (button_state, true);
343         } else {
344                 DEBUG_TRACE (DEBUG::CC121, "button was consumed, ignored\n");
345                 consumed.erase (c);
346         }
347 }
348
349 void
350 CC121::button_release_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
351 {
352         DEBUG_TRACE (DEBUG::CC121, string_compose ("button release event for ID %1 release ? %2\n", (int) tb->controller_number, (tb->value ? "yes" : "no")));
353
354         ButtonID id (ButtonID (tb->controller_number));
355         Button& button (get_button (id));
356
357         buttons_down.erase (id);
358         button.timeout_connection.disconnect ();
359
360         ButtonState bs (ButtonState (0));
361
362         switch (id) {
363         case FaderTouch:
364           fader_is_touched = false;
365           if (_current_stripable) {
366             boost::shared_ptr<AutomationControl> gain = _current_stripable->gain_control ();
367             if (gain) {
368               framepos_t now = session->engine().sample_time();
369               gain->stop_touch (true, now);
370             }
371           }
372           break;
373         default:
374                 break;
375         }
376
377         if (bs) {
378                 button_state = ButtonState (button_state&~bs);
379                 DEBUG_TRACE (DEBUG::CC121, string_compose ("reset button state to %1 using %2\n", button_state, (int) bs));
380         }
381
382         if (button.uses_flash()) {
383                 button.set_led_state (_output_port, (int)tb->value);
384         }
385
386         set<ButtonID>::iterator c = consumed.find (id);
387
388         if (c == consumed.end()) {
389                 button.invoke (button_state, false);
390         } else {
391                 DEBUG_TRACE (DEBUG::CC121, "button was consumed, ignored\n");
392                 consumed.erase (c);
393         }
394 }
395
396 void
397 CC121::encoder_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
398 {
399         DEBUG_TRACE (DEBUG::CC121, "encoder handler");
400
401         /* Extract absolute value*/
402         float adj = static_cast<float>(tb->value & ~0x40);
403
404         /* Get direction (negative values start at 0x40)*/
405         float sign = (tb->value & 0x40) ? -1.0 : 1.0;
406         switch(tb->controller_number) {
407         case 0x10:
408           /* pan */
409           DEBUG_TRACE (DEBUG::CC121, "PAN encoder");
410           if (_current_stripable) {
411             /* Get amount of change (encoder clicks) * (change per click)*/
412             /*Create an exponential curve*/
413             float curve = sign * pow(adj, (1.0 + 10.0) / 10.0);
414             adj = curve * (31 / 1000.0);
415             ardour_pan_azimuth (adj);
416           }
417           break;
418         case 0x20:
419           /* EQ 1 Q */
420           break;
421         case 0x21:
422           /* EQ 2 Q */
423           break;
424         case 0x22:
425           /* EQ 3 Q */
426           break;
427         case 0x23:
428           /* EQ 4 Q */
429           break;
430         case 0x30:
431           /* EQ 1 Frequency */
432           break;
433         case 0x31:
434           /* EQ 2 Frequency */
435           break;
436         case 0x32:
437           /* EQ 3 Frequency */
438           break;
439         case 0x33:
440           /* EQ 4 Frequency */
441           break;
442         case 0x3C:
443           /* AI */
444           if (sign < 0.0f) {
445             if (_jogmode == scroll) {
446               ScrollTimeline(-0.05);
447             }
448             else {
449               ZoomIn();
450             }
451           }
452           else {
453             if (_jogmode == scroll) {
454               ScrollTimeline(0.05);
455             }
456             else {
457               ZoomOut();
458             }
459           }
460           break;
461         case 0x40:
462           /* EQ 1 Gain */
463           break;
464         case 0x41:
465           /* EQ 2 Gain */
466           break;
467         case 0x42:
468           /* EQ 3 Gain */
469           break;
470         case 0x43:
471           /* EQ 4 Gain */
472           break;
473         case 0x50:
474           /* Value */
475           break;
476         default:
477           break;
478         }
479 }
480
481 void
482 CC121::fader_handler (MIDI::Parser &, MIDI::pitchbend_t pb)
483 {
484         DEBUG_TRACE (DEBUG::CC121, "fader handler");
485
486         if (_current_stripable) {
487           boost::shared_ptr<AutomationControl> gain = _current_stripable->gain_control ();
488           if (gain) {
489             float val = gain->interface_to_internal (pb/16384.0);
490             /* even though the cc121 only controls a
491                single stripable at a time, allow the fader to
492                modify the group, if appropriate.
493             */
494             _current_stripable->gain_control()->set_value (val, Controllable::UseGroup);
495           }
496         }
497 }
498
499 int
500 CC121::set_active (bool yn)
501 {
502         DEBUG_TRACE (DEBUG::CC121, string_compose("CC121::set_active init with yn: '%1'\n", yn));
503
504         if (yn == active()) {
505                 return 0;
506         }
507
508         if (yn) {
509
510                 /* start event loop */
511
512                 BaseUI::run ();
513
514                 connect_session_signals ();
515
516                 Glib::RefPtr<Glib::TimeoutSource> blink_timeout = Glib::TimeoutSource::create (200); // milliseconds
517                 blink_connection = blink_timeout->connect (sigc::mem_fun (*this, &CC121::blink));
518                 blink_timeout->attach (main_loop()->get_context());
519
520                 Glib::RefPtr<Glib::TimeoutSource> heartbeat_timeout = Glib::TimeoutSource::create (800); // milliseconds
521                 heartbeat_connection = heartbeat_timeout->connect (sigc::mem_fun (*this, &CC121::beat));
522                 heartbeat_timeout->attach (main_loop()->get_context());
523
524                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
525                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &CC121::periodic));
526                 periodic_timeout->attach (main_loop()->get_context());
527
528         } else {
529
530                 BaseUI::quit ();
531                 close ();
532
533         }
534
535         ControlProtocol::set_active (yn);
536
537         DEBUG_TRACE (DEBUG::CC121, string_compose("CC121::set_active done with yn: '%1'\n", yn));
538
539         return 0;
540 }
541
542 bool
543 CC121::periodic ()
544 {
545         if (!_current_stripable) {
546                 return true;
547         }
548
549         ARDOUR::AutoState gain_state = _current_stripable->gain_control()->automation_state();
550
551         if (gain_state == ARDOUR::Touch || gain_state == ARDOUR::Play) {
552                 map_gain ();
553         }
554
555         return true;
556 }
557
558 void
559 CC121::stop_blinking (ButtonID id)
560 {
561         blinkers.remove (id);
562         get_button (id).set_led_state (_output_port, false);
563 }
564
565 void
566 CC121::start_blinking (ButtonID id)
567 {
568         blinkers.push_back (id);
569         get_button (id).set_led_state (_output_port, true);
570 }
571
572 bool
573 CC121::beat ()
574 {
575         MIDI::byte buf[8];
576
577         buf[0] = 0xf0;
578         buf[1] = 0x43;
579         buf[2] = 0x10;
580         buf[3] = 0x3e;
581         buf[4] = 0x15;
582         buf[5] = 0x00;
583         buf[6] = 0x01;
584         buf[7] = 0xF7;
585
586         _output_port->write (buf, 8, 0);
587
588         return true;
589 }
590
591 bool
592 CC121::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         map_recenable_state ();
601
602         return true;
603 }
604
605 void
606 CC121::close ()
607 {
608         all_lights_out ();
609
610         stop_midi_handling ();
611         session_connections.drop_connections ();
612         port_connection.disconnect ();
613         blink_connection.disconnect ();
614         heartbeat_connection.disconnect ();
615         selection_connection.disconnect ();
616         stripable_connections.drop_connections ();
617
618 #if 0
619         stripable_connections.drop_connections ();
620 #endif
621 }
622
623 void
624 CC121::map_recenable_state ()
625 {
626         /* special case for RecEnable because its status can change as a
627          * confluence of unrelated parameters: (a) session rec-enable state (b)
628          * rec-enabled tracks. So we don't add the button to the blinkers list,
629          * we just call this:
630          *
631          *  * from the blink callback
632          *  * when the session tells us about a status change
633          *
634          * We do the last one so that the button changes state promptly rather
635          * than waiting for the next blink callback. The change in "blinking"
636          * based on having record-enabled tracks isn't urgent, and that happens
637          * during the blink callback.
638          */
639
640         bool onoff;
641
642         switch (session->record_status()) {
643         case Session::Disabled:
644                 onoff = false;
645                 break;
646         case Session::Enabled:
647                 onoff = blink_state;
648                 break;
649         case Session::Recording:
650                 if (session->have_rec_enabled_track ()) {
651                         onoff = true;
652                 } else {
653                         onoff = blink_state;
654                 }
655                 break;
656         }
657
658         if (onoff != rec_enable_state) {
659                 get_button(RecEnable).set_led_state (_output_port, onoff);
660                 rec_enable_state = onoff;
661         }
662 }
663
664 void
665 CC121::map_transport_state ()
666 {
667         get_button (Loop).set_led_state (_output_port, session->get_play_loop());
668
669         float ts = session->transport_speed();
670
671         if (ts == 0) {
672                 stop_blinking (Play);
673         } else if (fabs (ts) == 1.0) {
674                 stop_blinking (Play);
675                 get_button (Play).set_led_state (_output_port, true);
676         } else {
677                 start_blinking (Play);
678         }
679
680         get_button (Stop).set_led_state (_output_port, session->transport_stopped ());
681         get_button (Rewind).set_led_state (_output_port, session->transport_speed() < 0.0);
682         get_button (Ffwd).set_led_state (_output_port, session->transport_speed() > 1.0);
683         get_button (Jog).set_led_state (_output_port, _jogmode == scroll);
684 }
685
686 void
687 CC121::connect_session_signals()
688 {
689         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_recenable_state, this), this);
690         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_transport_state, this), this);
691 }
692
693 bool
694 CC121::midi_input_handler (Glib::IOCondition ioc, boost::shared_ptr<ARDOUR::AsyncMIDIPort> port)
695 {
696         DEBUG_TRACE (DEBUG::CC121, string_compose ("something happend on  %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
697
698         if (ioc & ~IO_IN) {
699                 return false;
700         }
701
702         if (ioc & IO_IN) {
703
704                 port->clear ();
705                 DEBUG_TRACE (DEBUG::CC121, string_compose ("data available on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
706                 framepos_t now = session->engine().sample_time();
707                 port->parse (now);
708         }
709
710         return true;
711 }
712
713
714 XMLNode&
715 CC121::get_state ()
716 {
717         XMLNode& node (ControlProtocol::get_state());
718
719         XMLNode* child;
720
721         child = new XMLNode (X_("Input"));
722         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_input_port)->get_state());
723         node.add_child_nocopy (*child);
724
725
726         child = new XMLNode (X_("Output"));
727         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_output_port)->get_state());
728         node.add_child_nocopy (*child);
729
730         /* Save action state for Function1..4, Lock, Value, EQnEnable, EQType,
731          * AllBypass and Footswitch buttons, since these
732          * are user controlled. We can only save named-action operations, since
733          * internal functions are just pointers to functions and hard to
734          * serialize without enumerating them all somewhere.
735          */
736
737         node.add_child_nocopy (get_button (Function1).get_state());
738         node.add_child_nocopy (get_button (Function2).get_state());
739         node.add_child_nocopy (get_button (Function3).get_state());
740         node.add_child_nocopy (get_button (Function4).get_state());
741         node.add_child_nocopy (get_button (Value).get_state());
742         node.add_child_nocopy (get_button (Lock).get_state());
743         node.add_child_nocopy (get_button (EQ1Enable).get_state());
744         node.add_child_nocopy (get_button (EQ2Enable).get_state());
745         node.add_child_nocopy (get_button (EQ3Enable).get_state());
746         node.add_child_nocopy (get_button (EQ4Enable).get_state());
747         node.add_child_nocopy (get_button (EQType).get_state());
748         node.add_child_nocopy (get_button (AllBypass).get_state());
749         node.add_child_nocopy (get_button (Footswitch).get_state());
750
751         return node;
752 }
753
754 int
755 CC121::set_state (const XMLNode& node, int version)
756 {
757         XMLNodeList nlist;
758         XMLNodeConstIterator niter;
759         XMLNode const* child;
760
761         if (ControlProtocol::set_state (node, version)) {
762                 return -1;
763         }
764
765         if ((child = node.child (X_("Input"))) != 0) {
766                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
767                 if (portnode) {
768                         boost::shared_ptr<ARDOUR::Port>(_input_port)->set_state (*portnode, version);
769                 }
770         }
771
772         if ((child = node.child (X_("Output"))) != 0) {
773                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
774                 if (portnode) {
775                         boost::shared_ptr<ARDOUR::Port>(_output_port)->set_state (*portnode, version);
776                 }
777         }
778
779         for (XMLNodeList::const_iterator n = node.children().begin(); n != node.children().end(); ++n) {
780                 if ((*n)->name() == X_("Button")) {
781                         XMLProperty const * prop = (*n)->property (X_("id"));
782                         if (!prop) {
783                                 continue;
784                         }
785                         int xid = atoi (prop->value());
786                         ButtonMap::iterator b = buttons.find (ButtonID (xid));
787                         if (b == buttons.end()) {
788                                 continue;
789                         }
790                         b->second.set_state (**n);
791                 }
792         }
793
794         return 0;
795 }
796
797 bool
798 CC121::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
799 {
800         DEBUG_TRACE (DEBUG::CC121, "CC121::connection_handler  start\n");
801         if (!_input_port || !_output_port) {
802                 return false;
803         }
804
805         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
806         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
807
808         if (ni == name1 || ni == name2) {
809                 if (yn) {
810                         connection_state |= InputConnected;
811                 } else {
812                         connection_state &= ~InputConnected;
813                 }
814         } else if (no == name1 || no == name2) {
815                 if (yn) {
816                         connection_state |= OutputConnected;
817                 } else {
818                         connection_state &= ~OutputConnected;
819                 }
820         } else {
821                 DEBUG_TRACE (DEBUG::CC121, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
822                 /* not our ports */
823                 return false;
824         }
825
826         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
827
828                 /* XXX this is a horrible hack. Without a short sleep here,
829                    something prevents the device wakeup messages from being
830                    sent and/or the responses from being received.
831                 */
832
833                 g_usleep (100000);
834                 DEBUG_TRACE (DEBUG::CC121, "device now connected for both input and output\n");
835                 connected ();
836
837         } else {
838                 DEBUG_TRACE (DEBUG::CC121, "Device disconnected (input or output or both) or not yet fully connected\n");
839                 _device_active = false;
840         }
841
842         ConnectionChange (); /* emit signal for our GUI */
843
844         DEBUG_TRACE (DEBUG::CC121, "CC121::connection_handler  end\n");
845
846         return true; /* connection status changed */
847 }
848
849 void
850 CC121::connected ()
851 {
852         DEBUG_TRACE (DEBUG::CC121, "connected");
853
854         _device_active = true;
855
856         start_midi_handling ();
857
858         all_lights_out ();
859
860         /* catch up on state */
861
862         /* make sure that rec_enable_state is consistent with current device state */
863         get_button (RecEnable).set_led_state (_output_port, rec_enable_state);
864
865         map_transport_state ();
866         map_recenable_state ();
867 }
868
869 void
870 CC121::Button::invoke (CC121::ButtonState bs, bool press)
871 {
872         DEBUG_TRACE (DEBUG::CC121, string_compose ("invoke button %1 for %2 state %3%4%5\n", id, (press ? "press":"release"), hex, bs, dec));
873
874         ToDoMap::iterator x;
875
876         if (press) {
877                 if ((x = on_press.find (bs)) == on_press.end()) {
878                         DEBUG_TRACE (DEBUG::CC121, string_compose ("no press action for button %1 state %2 @ %3 in %4\n", id, bs, this, &on_press));
879                         return;
880                 }
881         } else {
882                 if ((x = on_release.find (bs)) == on_release.end()) {
883                         DEBUG_TRACE (DEBUG::CC121, string_compose ("no release action for button %1 state %2 @%3 in %4\n", id, bs, this, &on_release));
884                         return;
885                 }
886         }
887
888         switch (x->second.type) {
889         case NamedAction:
890                 if (!x->second.action_name.empty()) {
891                         fp.access_action (x->second.action_name);
892                 }
893                 break;
894         case InternalFunction:
895                 if (x->second.function) {
896                         x->second.function ();
897                 }
898         }
899 }
900
901 void
902 CC121::Button::set_action (string const& name, bool when_pressed, CC121::ButtonState bs)
903 {
904         ToDo todo;
905
906         todo.type = NamedAction;
907
908         if (when_pressed) {
909                 if (name.empty()) {
910                         on_press.erase (bs);
911                 } else {
912                         DEBUG_TRACE (DEBUG::CC121, string_compose ("set button %1 to action %2 on press + %3%4%5\n", id, name, bs));
913                         todo.action_name = name;
914                         on_press[bs] = todo;
915                 }
916         } else {
917                 if (name.empty()) {
918                         on_release.erase (bs);
919                 } else {
920                         DEBUG_TRACE (DEBUG::CC121, string_compose ("set button %1 to action %2 on release + %3%4%5\n", id, name, bs));
921                         todo.action_name = name;
922                         on_release[bs] = todo;
923                 }
924         }
925 }
926
927 string
928 CC121::Button::get_action (bool press, CC121::ButtonState bs)
929 {
930         ToDoMap::iterator x;
931
932         if (press) {
933                 if ((x = on_press.find (bs)) == on_press.end()) {
934                         return string();
935                 }
936                 if (x->second.type != NamedAction) {
937                         return string ();
938                 }
939                 return x->second.action_name;
940         } else {
941                 if ((x = on_release.find (bs)) == on_release.end()) {
942                         return string();
943                 }
944                 if (x->second.type != NamedAction) {
945                         return string ();
946                 }
947                 return x->second.action_name;
948         }
949 }
950
951 void
952 CC121::Button::set_action (boost::function<void()> f, bool when_pressed, CC121::ButtonState bs)
953 {
954         ToDo todo;
955         todo.type = InternalFunction;
956
957         if (when_pressed) {
958                 DEBUG_TRACE (DEBUG::CC121, string_compose ("set button %1 (%2) @ %5 to some functor on press + %3 in %4\n", id, name, bs, &on_press, this));
959                 todo.function = f;
960                 on_press[bs] = todo;
961         } else {
962                 DEBUG_TRACE (DEBUG::CC121, string_compose ("set button %1 (%2) @ %5 to some functor on release + %3\n", id, name, bs, this));
963                 todo.function = f;
964                 on_release[bs] = todo;
965         }
966 }
967
968 void
969 CC121::Button::set_led_state (boost::shared_ptr<MIDI::Port> port, bool onoff)
970 {
971         MIDI::byte buf[3];
972         DEBUG_TRACE(DEBUG::CC121, "Set Led State\n");
973         buf[0] = 0x90;
974         buf[1] = id;
975         buf[2] = (onoff ? 0x7F:0x00);
976         port->write (buf, 3, 0);
977 }
978
979 int
980 CC121::Button::set_state (XMLNode const& node)
981 {
982         const XMLProperty* prop = node.property ("id");
983         if (!prop) {
984                 return -1;
985         }
986
987         int xid = atoi (prop->value());
988         if (xid != id) {
989                 return -1;
990         }
991
992         typedef pair<string,CC121::ButtonState> state_pair_t;
993         vector<state_pair_t> state_pairs;
994
995         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
996
997         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
998                 string propname;
999
1000                 propname = sp->first + X_("-press");
1001                 if ((prop = node.property (propname)) != 0) {
1002                         set_action (prop->value(), true, sp->second);
1003                 }
1004
1005                 propname = sp->first + X_("-release");
1006                 if ((prop = node.property (propname)) != 0) {
1007                         set_action (prop->value(), false, sp->second);
1008                 }
1009         }
1010
1011         return 0;
1012 }
1013
1014 XMLNode&
1015 CC121::Button::get_state () const
1016 {
1017         XMLNode* node = new XMLNode (X_("Button"));
1018         char buf[16];
1019         snprintf (buf, sizeof (buf), "%d", id);
1020
1021         node->add_property (X_("id"), buf);
1022
1023         ToDoMap::const_iterator x;
1024         ToDo null;
1025         null.type = NamedAction;
1026
1027         typedef pair<string,CC121::ButtonState> state_pair_t;
1028         vector<state_pair_t> state_pairs;
1029
1030         state_pairs.push_back (make_pair (string ("plain"), ButtonState (0)));
1031
1032         for (vector<state_pair_t>::const_iterator sp = state_pairs.begin(); sp != state_pairs.end(); ++sp) {
1033                 if ((x = on_press.find (sp->second)) != on_press.end()) {
1034                         if (x->second.type == NamedAction) {
1035                                 node->add_property (string (sp->first + X_("-press")).c_str(), x->second.action_name);
1036                         }
1037                 }
1038
1039                 if ((x = on_release.find (sp->second)) != on_release.end()) {
1040                         if (x->second.type == NamedAction) {
1041                                 node->add_property (string (sp->first + X_("-release")).c_str(), x->second.action_name);
1042                         }
1043                 }
1044         }
1045
1046         return *node;
1047 }
1048
1049 void
1050 CC121::gui_track_selection_changed (StripableNotificationListPtr stripables)
1051 {
1052         boost::shared_ptr<Stripable> r;
1053
1054         if (!stripables->empty()) {
1055                 r = stripables->front().lock();
1056         }
1057
1058         set_current_stripable (r);
1059 }
1060
1061 void
1062 CC121::drop_current_stripable ()
1063 {
1064         if (_current_stripable) {
1065                 if (_current_stripable == session->monitor_out()) {
1066                         set_current_stripable (session->master_out());
1067                 } else {
1068                         set_current_stripable (boost::shared_ptr<Stripable>());
1069                 }
1070         }
1071 }
1072
1073 void
1074 CC121::set_current_stripable (boost::shared_ptr<Stripable> r)
1075 {
1076         stripable_connections.drop_connections ();
1077
1078         _current_stripable = r;
1079
1080         if (_current_stripable) {
1081                 _current_stripable->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::drop_current_stripable, this), this);
1082
1083                 _current_stripable->mute_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_mute, this), this);
1084                 _current_stripable->solo_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_solo, this), this);
1085
1086                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_stripable);
1087                 if (t) {
1088                         t->rec_enable_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_recenable, this), this);
1089                 }
1090
1091                 boost::shared_ptr<AutomationControl> control = _current_stripable->gain_control ();
1092                 if (control) {
1093                         control->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_gain, this), this);
1094                         control->alist()->automation_state_changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_auto, this), this);
1095                 }
1096
1097                 boost::shared_ptr<MonitorProcessor> mp = _current_stripable->monitor_control();
1098                 if (mp) {
1099                         mp->cut_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&CC121::map_cut, this), this);
1100                 }
1101         }
1102
1103         //ToDo: subscribe to the fader automation modes so we can light the LEDs
1104
1105         map_stripable_state ();
1106 }
1107
1108 void
1109 CC121::map_auto ()
1110 {
1111         boost::shared_ptr<AutomationControl> control = _current_stripable->gain_control ();
1112         const AutoState as = control->automation_state ();
1113
1114         switch (as) {
1115                 case ARDOUR::Play:
1116                         get_button (FP_Read).set_led_state (_output_port, true);
1117                         get_button (FP_Write).set_led_state (_output_port, false);
1118                         get_button (EButton).set_led_state (_output_port, false);
1119                         get_button (OpenVST).set_led_state (_output_port, false);
1120                 break;
1121                 case ARDOUR::Write:
1122                         get_button (FP_Read).set_led_state (_output_port, false);
1123                         get_button (FP_Write).set_led_state (_output_port, true);
1124                         get_button (EButton).set_led_state (_output_port, false);
1125                         get_button (OpenVST).set_led_state (_output_port, false);
1126                 break;
1127                 case ARDOUR::Touch:
1128                         get_button (EButton).set_led_state (_output_port, true);
1129                         get_button (FP_Read).set_led_state (_output_port, false);
1130                         get_button (FP_Write).set_led_state(_output_port, false);
1131                         get_button (OpenVST).set_led_state (_output_port, false);
1132                 break;
1133                 case ARDOUR::Off:
1134                         get_button (OpenVST).set_led_state (_output_port, true);
1135                         get_button (FP_Read).set_led_state (_output_port, false);
1136                         get_button (FP_Write).set_led_state (_output_port, false);
1137                         get_button (EButton).set_led_state (_output_port, false);
1138                 break;
1139         }
1140 }
1141
1142 void
1143 CC121::map_cut ()
1144 {
1145         boost::shared_ptr<MonitorProcessor> mp = _current_stripable->monitor_control();
1146
1147         if (mp) {
1148                 bool yn = mp->cut_all ();
1149                 if (yn) {
1150                         start_blinking (Mute);
1151                 } else {
1152                         stop_blinking (Mute);
1153                 }
1154         } else {
1155                 stop_blinking (Mute);
1156         }
1157 }
1158
1159 void
1160 CC121::map_mute ()
1161 {
1162         if (_current_stripable) {
1163                 if (_current_stripable->mute_control()->muted()) {
1164                         stop_blinking (Mute);
1165                         get_button (Mute).set_led_state (_output_port, true);
1166                 } else if (_current_stripable->mute_control()->muted_by_others_soloing () || _current_stripable->mute_control()->muted_by_masters()) {
1167                         start_blinking (Mute);
1168                 } else {
1169                         stop_blinking (Mute);
1170                 }
1171         } else {
1172                 stop_blinking (Mute);
1173         }
1174 }
1175
1176 void
1177 CC121::map_solo ()
1178 {
1179         if (_current_stripable) {
1180                 get_button (Solo).set_led_state (_output_port, _current_stripable->solo_control()->soloed());
1181         } else {
1182                 get_button (Solo).set_led_state (_output_port, false);
1183         }
1184 }
1185
1186 void
1187 CC121::map_recenable ()
1188 {
1189         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (_current_stripable);
1190         if (t) {
1191                 get_button (Rec).set_led_state (_output_port, t->rec_enable_control()->get_value());
1192         } else {
1193                 get_button (Rec).set_led_state (_output_port, false);
1194         }
1195 }
1196
1197 void
1198 CC121::map_gain ()
1199 {
1200         if (fader_is_touched) {
1201                 /* Do not send fader moves while the user is touching the fader */
1202                 return;
1203         }
1204
1205         if (!_current_stripable) {
1206                 return;
1207         }
1208
1209         boost::shared_ptr<AutomationControl> control = _current_stripable->gain_control ();
1210         double val;
1211
1212         if (!control) {
1213                 val = 0.0;
1214         } else {
1215                 val = control->internal_to_interface (control->get_value ());
1216         }
1217
1218         int ival = (int)((val * 16384.0f) + 0.5f);
1219         if (ival < 0) {
1220           ival = 0;
1221         }
1222         else if (ival > 16383) {
1223           ival = 16383;
1224         }
1225
1226         MIDI::byte buf[3];
1227
1228         buf[0] = 0xE0;
1229         buf[1] = ival & 0x7F;
1230         buf[2] = (ival >> 7) & 0x7F;
1231
1232         _output_port->write (buf, 3, 0);
1233 }
1234
1235 void
1236 CC121::map_stripable_state ()
1237 {
1238         if (!_current_stripable) {
1239                 stop_blinking (Mute);
1240                 stop_blinking (Solo);
1241                 get_button (Rec).set_led_state (_output_port, false);
1242         } else {
1243                 map_solo ();
1244                 map_recenable ();
1245                 map_gain ();
1246                 map_auto ();
1247
1248                 if (_current_stripable == session->monitor_out()) {
1249                         map_cut ();
1250                 } else {
1251                         map_mute ();
1252                 }
1253         }
1254 }
1255
1256 list<boost::shared_ptr<ARDOUR::Bundle> >
1257 CC121::bundles ()
1258 {
1259         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1260
1261         if (_input_bundle) {
1262                 b.push_back (_input_bundle);
1263                 b.push_back (_output_bundle);
1264         }
1265
1266         return b;
1267 }
1268
1269 boost::shared_ptr<Port>
1270 CC121::output_port()
1271 {
1272         return _output_port;
1273 }
1274
1275 boost::shared_ptr<Port>
1276 CC121::input_port()
1277 {
1278         return _input_port;
1279 }
1280
1281 void
1282 CC121::set_action (ButtonID id, std::string const& action_name, bool on_press, ButtonState bs)
1283 {
1284         get_button(id).set_action (action_name, on_press, bs);
1285 }
1286
1287 string
1288 CC121::get_action (ButtonID id, bool press, ButtonState bs)
1289 {
1290         return get_button(id).get_action (press, bs);
1291 }