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