ddefee3f5645503acf240cea603dba896d787e59
[ardour.git] / libs / surfaces / push2 / push2.cc
1 /*
2         Copyright (C) 2016 Paul Davis
3
4         This program is free software; you can redistribute it and/or modify
5         it under the terms of the GNU General Public License as published by
6         the Free Software Foundation; either version 2 of the License, or
7         (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12         GNU General Public License for more details.
13
14         You should have received a copy of the GNU General Public License
15         along with this program; if not, write to the Free Software
16         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <cairomm/context.h>
20 #include <cairomm/surface.h>
21 #include <pangomm/layout.h>
22
23 #include "pbd/compose.h"
24 #include "pbd/convert.h"
25 #include "pbd/debug.h"
26 #include "pbd/failed_constructor.h"
27
28 #include "midi++/parser.h"
29 #include "timecode/time.h"
30 #include "timecode/bbt_time.h"
31
32 #include "ardour/async_midi_port.h"
33 #include "ardour/audioengine.h"
34 #include "ardour/debug.h"
35 #include "ardour/midiport_manager.h"
36 #include "ardour/session.h"
37 #include "ardour/tempo.h"
38
39 #include "push2.h"
40
41 using namespace ARDOUR;
42 using namespace std;
43 using namespace PBD;
44 using namespace Glib;
45 using namespace ArdourSurface;
46
47 #include "i18n.h"
48
49 #include "pbd/abstract_ui.cc" // instantiate template
50
51 const int Push2::cols = 960;
52 const int Push2::rows = 160;
53 const int Push2::pixels_per_row = 1024;
54
55 #define ABLETON 0x2982
56 #define PUSH2   0x1967
57
58 Push2::Push2 (ARDOUR::Session& s)
59         : ControlProtocol (s, string (X_("Ableton Push 2")))
60         , AbstractUI<Push2Request> (name())
61         , handle (0)
62         , device_buffer (0)
63         , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
64         , modifier_state (None)
65         , bank_start (0)
66 {
67         context = Cairo::Context::create (frame_buffer);
68         tc_clock_layout = Pango::Layout::create (context);
69         bbt_clock_layout = Pango::Layout::create (context);
70
71         Pango::FontDescription fd ("Sans Bold 24");
72         tc_clock_layout->set_font_description (fd);
73         bbt_clock_layout->set_font_description (fd);
74
75         Pango::FontDescription fd2 ("Sans 10");
76         for (int n = 0; n < 8; ++n) {
77                 upper_layout[n] = Pango::Layout::create (context);
78                 upper_layout[n]->set_font_description (fd2);
79                 upper_layout[n]->set_text ("solo");
80                 lower_layout[n] = Pango::Layout::create (context);
81                 lower_layout[n]->set_font_description (fd2);
82                 lower_layout[n]->set_text ("mute");
83         }
84
85         Pango::FontDescription fd3 ("Sans Bold 10");
86         for (int n = 0; n < 8; ++n) {
87                 mid_layout[n] = Pango::Layout::create (context);
88                 mid_layout[n]->set_font_description (fd3);
89         }
90
91         build_maps ();
92
93         if (open ()) {
94                 throw failed_constructor ();
95         }
96
97 }
98
99 Push2::~Push2 ()
100 {
101         close ();
102 }
103
104 int
105 Push2::open ()
106 {
107         int err;
108
109         if (handle) {
110                 /* already open */
111                 return 0;
112         }
113
114         if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
115                 return -1;
116         }
117
118         if ((err = libusb_claim_interface (handle, 0x00))) {
119                 return -1;
120         }
121
122         device_frame_buffer = new uint16_t[rows*pixels_per_row];
123
124         memset (device_frame_buffer, 0, sizeof (uint16_t) * rows * pixels_per_row);
125
126         frame_header[0] = 0xef;
127         frame_header[1] = 0xcd;
128         frame_header[2] = 0xab;
129         frame_header[3] = 0x89;
130         memset (&frame_header[4], 0, 12);
131
132         /* setup ports */
133
134         _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in"), true);
135         _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out"), true);
136
137         if (_async_in == 0 || _async_out == 0) {
138                 return -1;
139         }
140
141         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
142         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
143
144         connect_to_parser ();
145
146         return 0;
147 }
148
149 int
150 Push2::close ()
151 {
152         AudioEngine::instance()->unregister_port (_async_in);
153         AudioEngine::instance()->unregister_port (_async_out);
154
155         _async_in.reset ((ARDOUR::Port*) 0);
156         _async_out.reset ((ARDOUR::Port*) 0);
157         _input_port = 0;
158         _output_port = 0;
159
160         vblank_connection.disconnect ();
161         periodic_connection.disconnect ();
162         session_connections.drop_connections ();
163         stripable_connections.drop_connections ();
164
165         if (handle) {
166                 libusb_release_interface (handle, 0x00);
167                 libusb_close (handle);
168                 handle = 0;
169         }
170
171         for (int n = 0; n < 8; ++n) {
172                 stripable[n].reset ();
173         }
174
175         delete [] device_frame_buffer;
176         device_frame_buffer = 0;
177
178         return 0;
179 }
180
181 void
182 Push2::init_buttons ()
183 {
184         ButtonID buttons[] = { Mute, Solo, Master, Up, Right, Left, Down, Note, Session, Mix, AddTrack, Delete, Undo,
185                                Metronome, Shift, Select, Play, RecordEnable, Automate, Repeat, Note, Session, DoubleLoop,
186                                Quantize, Duplicate,
187         };
188
189         for (size_t n = 0; n < sizeof (buttons) / sizeof (buttons[0]); ++n) {
190                 Button* b = id_button_map[buttons[n]];
191
192                 b->set_color (LED::White);
193                 b->set_state (LED::OneShot24th);
194                 write (b->state_msg());
195         }
196 }
197
198 bool
199 Push2::probe ()
200 {
201         libusb_device_handle *h;
202         libusb_init (NULL);
203
204         if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
205                 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
206                 return false;
207         }
208
209         libusb_close (h);
210         DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
211         return true;
212 }
213
214 void*
215 Push2::request_factory (uint32_t num_requests)
216 {
217         /* AbstractUI<T>::request_buffer_factory() is a template method only
218            instantiated in this source module. To provide something visible for
219            use in the interface/descriptor, we have this static method that is
220            template-free.
221         */
222         return request_buffer_factory (num_requests);
223 }
224
225 void
226 Push2::do_request (Push2Request * req)
227 {
228         DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
229         if (req->type == CallSlot) {
230
231                 call_slot (MISSING_INVALIDATOR, req->the_slot);
232
233         } else if (req->type == Quit) {
234
235                 stop ();
236         }
237 }
238
239 int
240 Push2::stop ()
241 {
242         BaseUI::quit ();
243         close ();
244         return 0;
245 }
246
247 /** render host-side frame buffer (a Cairo ImageSurface) to the current
248  * device-side frame buffer. The device frame buffer will be pushed to the
249  * device on the next call to vblank()
250  */
251
252 int
253 Push2::bitblt_to_device_frame_buffer ()
254 {
255         /* ensure that all drawing has been done before we fetch pixel data */
256
257         frame_buffer->flush ();
258
259         const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
260         const uint8_t* data = frame_buffer->get_data ();
261
262         /* fill frame buffer (320kB) */
263
264         uint16_t* fb = (uint16_t*) device_frame_buffer;
265
266         for (int row = 0; row < rows; ++row) {
267
268                 const uint8_t* dp = data + row * stride;
269
270                 for (int col = 0; col < cols; ++col) {
271
272                         /* fetch r, g, b (range 0..255). Ignore alpha */
273
274                         const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
275                         const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
276                         const int b = *((const uint32_t*)dp) & 0xff;
277
278                         /* convert to 5 bits, 6 bits, 5 bits, respectively */
279                         /* generate 16 bit BGB565 value */
280
281                         *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
282
283                         dp += 4;
284                 }
285
286                 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
287                    byte USB buffers
288                 */
289
290                 fb += 64; /* 128 bytes = 64 int16_t */
291         }
292
293         return 0;
294 }
295
296 bool
297 Push2::redraw ()
298 {
299         string tc_clock_text;
300         string bbt_clock_text;
301
302         if (session) {
303                 framepos_t audible = session->audible_frame();
304                 Timecode::Time TC;
305                 bool negative = false;
306
307                 if (audible < 0) {
308                         audible = -audible;
309                         negative = true;
310                 }
311
312                 session->timecode_time (audible, TC);
313
314                 TC.negative = TC.negative || negative;
315
316                 tc_clock_text = Timecode::timecode_format_time(TC);
317
318                 Timecode::BBT_Time bbt = session->tempo_map().bbt_at_frame (audible);
319                 char buf[16];
320
321 #define BBT_BAR_CHAR "|"
322
323                 if (negative) {
324                         snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
325                                   bbt.bars, bbt.beats, bbt.ticks);
326                 } else {
327                         snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
328                                   bbt.bars, bbt.beats, bbt.ticks);
329                 }
330
331                 bbt_clock_text = buf;
332         }
333
334         bool dirty = false;
335
336         if (tc_clock_text != tc_clock_layout->get_text()) {
337                 dirty = true;
338                 tc_clock_layout->set_text (tc_clock_text);
339         }
340
341         if (bbt_clock_text != tc_clock_layout->get_text()) {
342                 dirty = true;
343                 bbt_clock_layout->set_text (bbt_clock_text);
344         }
345
346         string mid_text;
347
348         for (int n = 0; n < 8; ++n) {
349                 if (stripable[n]) {
350                         mid_text = short_version (stripable[n]->name(), 10);
351                         if (mid_text != mid_layout[n]->get_text()) {
352                                 mid_layout[n]->set_text (mid_text);
353                                 dirty = true;
354                         }
355                 }
356         }
357
358         if (!dirty) {
359                 return false;
360         }
361
362         context->set_source_rgb (0.764, 0.882, 0.882);
363         context->rectangle (0, 0, 960, 160);
364         context->fill ();
365         context->set_source_rgb (0.23, 0.0, 0.349);
366         context->move_to (650, 25);
367         tc_clock_layout->update_from_cairo_context (context);
368         tc_clock_layout->show_in_cairo_context (context);
369         context->move_to (650, 60);
370         bbt_clock_layout->update_from_cairo_context (context);
371         bbt_clock_layout->show_in_cairo_context (context);
372
373         for (int n = 0; n < 8; ++n) {
374                 context->move_to (10 + (n*120), 2);
375                 upper_layout[n]->update_from_cairo_context (context);
376                 upper_layout[n]->show_in_cairo_context (context);
377         }
378
379         for (int n = 0; n < 8; ++n) {
380                 context->move_to (10 + (n*120), 140);
381                 lower_layout[n]->update_from_cairo_context (context);
382                 lower_layout[n]->show_in_cairo_context (context);
383         }
384
385         for (int n = 0; n < 8; ++n) {
386                 context->move_to (10 + (n*120), 120);
387                 context->set_source_rgb (0.0, 0.0, 0.0);
388                 mid_layout[n]->update_from_cairo_context (context);
389                 mid_layout[n]->show_in_cairo_context (context);
390         }
391
392         /* render clock */
393         /* render foo */
394         /* render bar */
395
396         return true;
397 }
398
399 bool
400 Push2::vblank ()
401 {
402         int transferred = 0;
403         const int timeout_msecs = 1000;
404         int err;
405
406         if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
407                 return false;
408         }
409
410         if (redraw()) {
411                 /* things changed */
412                 bitblt_to_device_frame_buffer ();
413         }
414
415         if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
416                 return false;
417         }
418
419         return true;
420 }
421
422 int
423 Push2::set_active (bool yn)
424 {
425         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
426
427         if (yn == active()) {
428                 return 0;
429         }
430
431         if (yn) {
432
433                 /* start event loop */
434
435                 BaseUI::run ();
436
437                 if (open ()) {
438                         DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
439                         close ();
440                         return -1;
441                 }
442
443                 /* Connect input port to event loop */
444
445                 AsyncMIDIPort* asp;
446
447                 asp = dynamic_cast<AsyncMIDIPort*> (_input_port);
448                 asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port));
449                 asp->xthread().attach (main_loop()->get_context());
450
451                 connect_session_signals ();
452
453                 /* set up periodic task used to push a frame buffer to the
454                  * device (25fps). The device can handle 60fps, but we don't
455                  * need that frame rate.
456                  */
457
458                 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
459                 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
460                 vblank_timeout->attach (main_loop()->get_context());
461
462
463                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (1000); // milliseconds
464                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
465                 periodic_timeout->attach (main_loop()->get_context());
466
467                 init_buttons ();
468                 init_touch_strip ();
469                 switch_bank (0);
470
471         } else {
472
473                 stop ();
474
475         }
476
477         ControlProtocol::set_active (yn);
478
479         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
480
481         return 0;
482 }
483
484 void
485 Push2::init_touch_strip ()
486 {
487         MidiByteArray msg (9, 0xf0, 0x00, 0x21, 0x1d, 0x01, 0x01, 0x17, 0x00, 0xf7);
488         /* flags are the final byte (ignore end-of-sysex */
489
490         /* show bar, not point
491            autoreturn to center
492            bar starts at center
493         */
494         msg[7] = (1<<4) | (1<<5) | (1<<6);
495         write (msg);
496 }
497
498 void
499 Push2::write (const MidiByteArray& data)
500 {
501         cerr << data << endl;
502         /* immediate delivery */
503         _output_port->write (&data[0], data.size(), 0);
504 }
505
506 bool
507 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
508 {
509         if (ioc & ~IO_IN) {
510                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
511                 return false;
512         }
513
514         if (ioc & IO_IN) {
515
516                 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
517
518                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
519                 if (asp) {
520                         asp->clear ();
521                 }
522
523                 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
524                 framepos_t now = AudioEngine::instance()->sample_time();
525                 port->parse (now);
526         }
527
528         return true;
529 }
530
531 bool
532 Push2::periodic ()
533 {
534         return true;
535 }
536
537 void
538 Push2::connect_to_parser ()
539 {
540         DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
541
542         MIDI::Parser* p = _input_port->parser();
543
544         /* Incoming sysex */
545         p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
546         /* V-Pot messages are Controller */
547         p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
548         /* Button messages are NoteOn */
549         p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
550         /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
551         p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
552         /* Fader messages are Pitchbend */
553         p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
554 }
555
556 void
557 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
558 {
559         cerr << "sysex, " << sz << " bytes\n";
560 }
561
562 void
563 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
564 {
565         CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
566
567         if (b != cc_button_map.end()) {
568                 if (ev->value == 0) {
569                         (this->*b->second->release_method)();
570                 } else {
571                         (this->*b->second->press_method)();
572                 }
573         } else {
574
575                 /* encoder/vpot */
576
577                 int delta = ev->value;
578
579                 if (delta > 63) {
580                         delta = -(128 - delta);
581                 }
582
583                 switch (ev->controller_number) {
584                 case 71:
585                         strip_vpot (0, delta);
586                         break;
587                 case 72:
588                         strip_vpot (1, delta);
589                         break;
590                 case 73:
591                         strip_vpot (2, delta);
592                         break;
593                 case 74:
594                         strip_vpot (3, delta);
595                         break;
596                 case 75:
597                         strip_vpot (4, delta);
598                         break;
599                 case 76:
600                         strip_vpot (5, delta);
601                         break;
602                 case 77:
603                         strip_vpot (6, delta);
604                         break;
605                 case 78:
606                         strip_vpot (7, delta);
607                         break;
608
609                         /* left side pair */
610                 case 14:
611                         strip_vpot (8, delta);
612                         break;
613                 case 15:
614                         other_vpot (1, delta);
615                         break;
616
617                         /* right side */
618                 case 79:
619                         other_vpot (2, delta);
620                         break;
621                 }
622         }
623 }
624
625 void
626 Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
627 {
628         switch (ev->note_number) {
629         case 0:
630                 strip_vpot_touch (0, ev->velocity > 64);
631                 break;
632         case 1:
633                 strip_vpot_touch (1, ev->velocity > 64);
634                 break;
635         case 2:
636                 strip_vpot_touch (2, ev->velocity > 64);
637                 break;
638         case 3:
639                 strip_vpot_touch (3, ev->velocity > 64);
640                 break;
641         case 4:
642                 strip_vpot_touch (4, ev->velocity > 64);
643                 break;
644         case 5:
645                 strip_vpot_touch (5, ev->velocity > 64);
646                 break;
647         case 6:
648                 strip_vpot_touch (6, ev->velocity > 64);
649                 break;
650         case 7:
651                 strip_vpot_touch (7, ev->velocity > 64);
652                 break;
653
654                 /* left side */
655         case 10:
656                 other_vpot_touch (0, ev->velocity > 64);
657                 break;
658         case 9:
659                 other_vpot_touch (1, ev->velocity > 64);
660                 break;
661
662                 /* right side */
663         case 8:
664                 other_vpot_touch (3, ev->velocity > 64);
665                 break;
666
667                 /* touch strip */
668         case 12:
669                 if (ev->velocity < 64) {
670                         transport_stop ();
671                 }
672                 break;
673         }
674
675 }
676
677 void
678 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
679 {
680 }
681
682 void
683 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
684 {
685         if (!session) {
686                 return;
687         }
688         float speed;
689
690         /* range of +1 .. -1 */
691         speed = ((int32_t) pb - 8192) / 8192.0;
692         /* convert to range of +3 .. -3 */
693         session->request_transport_speed (speed * 3.0);
694 }
695
696 void
697 Push2::build_maps ()
698 {
699         /* Pads */
700
701         Pad* pad;
702
703 #define MAKE_PAD(x,y,nn) \
704         pad = new Pad ((x), (y), (nn)); \
705         nn_pad_map.insert (make_pair (pad->extra(), pad)); \
706         coord_pad_map.insert (make_pair (pad->coord(), pad));
707
708         MAKE_PAD (0, 1, 93);
709         MAKE_PAD (0, 2, 94);
710         MAKE_PAD (0, 3, 95);
711         MAKE_PAD (0, 4, 96);
712         MAKE_PAD (0, 5, 97);
713         MAKE_PAD (0, 6, 98);
714         MAKE_PAD (0, 7, 90);
715         MAKE_PAD (1, 0, 84);
716         MAKE_PAD (1, 1, 85);
717         MAKE_PAD (1, 2, 86);
718         MAKE_PAD (1, 3, 87);
719         MAKE_PAD (1, 4, 88);
720         MAKE_PAD (1, 5, 89);
721         MAKE_PAD (1, 6, 90);
722         MAKE_PAD (1, 7, 91);
723         MAKE_PAD (2, 0, 76);
724         MAKE_PAD (2, 1, 77);
725         MAKE_PAD (2, 2, 78);
726         MAKE_PAD (2, 3, 79);
727         MAKE_PAD (2, 4, 80);
728         MAKE_PAD (2, 5, 81);
729         MAKE_PAD (2, 6, 82);
730         MAKE_PAD (2, 7, 83);
731         MAKE_PAD (3, 0, 68);
732         MAKE_PAD (3, 1, 69);
733         MAKE_PAD (3, 2, 70);
734         MAKE_PAD (3, 3, 71);
735         MAKE_PAD (3, 4, 72);
736         MAKE_PAD (3, 5, 73);
737         MAKE_PAD (3, 6, 74);
738         MAKE_PAD (3, 7, 75);
739         MAKE_PAD (4, 0, 60);
740         MAKE_PAD (4, 1, 61);
741         MAKE_PAD (4, 2, 62);
742         MAKE_PAD (4, 3, 63);
743         MAKE_PAD (4, 4, 64);
744         MAKE_PAD (4, 5, 65);
745         MAKE_PAD (4, 6, 66);
746         MAKE_PAD (4, 7, 67);
747         MAKE_PAD (5, 0, 52);
748         MAKE_PAD (5, 1, 53);
749         MAKE_PAD (5, 2, 54);
750         MAKE_PAD (5, 3, 56);
751         MAKE_PAD (5, 4, 56);
752         MAKE_PAD (5, 5, 57);
753         MAKE_PAD (5, 6, 58);
754         MAKE_PAD (5, 7, 59);
755         MAKE_PAD (6, 0, 44);
756         MAKE_PAD (6, 1, 45);
757         MAKE_PAD (6, 2, 46);
758         MAKE_PAD (6, 3, 47);
759         MAKE_PAD (6, 4, 48);
760         MAKE_PAD (6, 5, 49);
761         MAKE_PAD (6, 6, 50);
762         MAKE_PAD (6, 7, 51);
763         MAKE_PAD (7, 0, 36);
764         MAKE_PAD (7, 1, 37);
765         MAKE_PAD (7, 2, 38);
766         MAKE_PAD (7, 3, 39);
767         MAKE_PAD (7, 4, 40);
768         MAKE_PAD (7, 5, 41);
769         MAKE_PAD (7, 6, 42);
770         MAKE_PAD (7, 7, 43);
771
772         /* Now color buttons */
773
774         Button *button;
775
776 #define MAKE_COLOR_BUTTON(i,cc) \
777         button = new ColorButton ((i), (cc)); \
778         cc_button_map.insert (make_pair (button->controller_number(), button)); \
779         id_button_map.insert (make_pair (button->id, button));
780 #define MAKE_COLOR_BUTTON_PRESS(i,cc,p)\
781         button = new ColorButton ((i), (cc), (p)); \
782         cc_button_map.insert (make_pair (button->controller_number(), button)); \
783         id_button_map.insert (make_pair (button->id, button))
784
785         MAKE_COLOR_BUTTON_PRESS (Upper1, 102, &Push2::button_upper_1);
786         MAKE_COLOR_BUTTON_PRESS (Upper2, 103, &Push2::button_upper_2);
787         MAKE_COLOR_BUTTON_PRESS (Upper3, 104, &Push2::button_upper_3);
788         MAKE_COLOR_BUTTON_PRESS (Upper4, 105, &Push2::button_upper_4);
789         MAKE_COLOR_BUTTON_PRESS (Upper5, 106, &Push2::button_upper_5);
790         MAKE_COLOR_BUTTON_PRESS (Upper6, 107, &Push2::button_upper_6);
791         MAKE_COLOR_BUTTON_PRESS (Upper7, 108, &Push2::button_upper_7);
792         MAKE_COLOR_BUTTON_PRESS (Upper8, 109, &Push2::button_upper_8);
793         MAKE_COLOR_BUTTON_PRESS (Lower1, 20, &Push2::button_lower_1);
794         MAKE_COLOR_BUTTON_PRESS (Lower2, 21, &Push2::button_lower_2);
795         MAKE_COLOR_BUTTON_PRESS (Lower3, 22, &Push2::button_lower_3);
796         MAKE_COLOR_BUTTON_PRESS (Lower4, 23, &Push2::button_lower_4);
797         MAKE_COLOR_BUTTON_PRESS (Lower5, 24, &Push2::button_lower_5);
798         MAKE_COLOR_BUTTON_PRESS (Lower6, 25, &Push2::button_lower_6);
799         MAKE_COLOR_BUTTON_PRESS (Lower7, 26, &Push2::button_lower_7);
800         MAKE_COLOR_BUTTON_PRESS (Lower8, 27, &Push2::button_lower_8);
801         MAKE_COLOR_BUTTON (Master, 28);
802         MAKE_COLOR_BUTTON (Mute, 60);
803         MAKE_COLOR_BUTTON_PRESS (Solo, 61, &Push2::button_solo);
804         MAKE_COLOR_BUTTON (Stop, 29);
805         MAKE_COLOR_BUTTON_PRESS (Fwd32ndT, 43, &Push2::button_fwd32t);
806         MAKE_COLOR_BUTTON_PRESS (Fwd32nd,42 , &Push2::button_fwd32);
807         MAKE_COLOR_BUTTON_PRESS (Fwd16thT, 41, &Push2::button_fwd16t);
808         MAKE_COLOR_BUTTON_PRESS (Fwd16th, 40, &Push2::button_fwd16);
809         MAKE_COLOR_BUTTON_PRESS (Fwd8thT, 39 , &Push2::button_fwd8t);
810         MAKE_COLOR_BUTTON_PRESS (Fwd8th, 38, &Push2::button_fwd8);
811         MAKE_COLOR_BUTTON_PRESS (Fwd4trT, 37, &Push2::button_fwd4t);
812         MAKE_COLOR_BUTTON_PRESS (Fwd4tr, 36, &Push2::button_fwd4);
813         MAKE_COLOR_BUTTON (Automate, 89);
814         MAKE_COLOR_BUTTON_PRESS (RecordEnable, 86, &Push2::button_recenable);
815         MAKE_COLOR_BUTTON_PRESS (Play, 85, &Push2::button_play);
816
817 #define MAKE_WHITE_BUTTON(i,cc)\
818         button = new WhiteButton ((i), (cc)); \
819         cc_button_map.insert (make_pair (button->controller_number(), button)); \
820         id_button_map.insert (make_pair (button->id, button))
821 #define MAKE_WHITE_BUTTON_PRESS(i,cc,p)\
822         button = new WhiteButton ((i), (cc), (p)); \
823         cc_button_map.insert (make_pair (button->controller_number(), button)); \
824         id_button_map.insert (make_pair (button->id, button))
825 #define MAKE_WHITE_BUTTON_PRESS_RELEASE(i,cc,p,r)                                \
826         button = new WhiteButton ((i), (cc), (p), (r)); \
827         cc_button_map.insert (make_pair (button->controller_number(), button)); \
828         id_button_map.insert (make_pair (button->id, button))
829
830         MAKE_WHITE_BUTTON (TapTempo, 3);
831         MAKE_WHITE_BUTTON_PRESS (Metronome, 9, &Push2::button_metronome);
832         MAKE_WHITE_BUTTON (Setup, 30);
833         MAKE_WHITE_BUTTON (User, 59);
834         MAKE_WHITE_BUTTON (Delete, 118);
835         MAKE_WHITE_BUTTON (AddDevice, 52);
836         MAKE_WHITE_BUTTON (Device, 110);
837         MAKE_WHITE_BUTTON (Mix, 112);
838         MAKE_WHITE_BUTTON_PRESS (Undo, 119, &Push2::button_undo);
839         MAKE_WHITE_BUTTON (AddTrack, 53);
840         MAKE_WHITE_BUTTON_PRESS (Browse, 111, &Push2::button_browse);
841         MAKE_WHITE_BUTTON_PRESS (Clip, 113, &Push2::button_clip);
842         MAKE_WHITE_BUTTON (Convert, 35);
843         MAKE_WHITE_BUTTON (DoubleLoop, 117);
844         MAKE_WHITE_BUTTON (Quantize, 116);
845         MAKE_WHITE_BUTTON (Duplicate, 88);
846         MAKE_WHITE_BUTTON_PRESS (New, 87, &Push2::button_new);
847         MAKE_WHITE_BUTTON_PRESS (FixedLength, 90, &Push2::button_fixed_length);
848         MAKE_WHITE_BUTTON_PRESS (Up, 46, &Push2::button_up);
849         MAKE_WHITE_BUTTON_PRESS (Right, 45, &Push2::button_right);
850         MAKE_WHITE_BUTTON_PRESS (Down, 47, &Push2::button_down);
851         MAKE_WHITE_BUTTON_PRESS (Left, 44, &Push2::button_left);
852         MAKE_WHITE_BUTTON_PRESS (Repeat, 56, &Push2::button_repeat);
853         MAKE_WHITE_BUTTON (Accent, 57);
854         MAKE_WHITE_BUTTON (Scale, 58);
855         MAKE_WHITE_BUTTON (Layout, 31);
856         MAKE_WHITE_BUTTON (Note, 50);
857         MAKE_WHITE_BUTTON (Session, 51);
858         MAKE_WHITE_BUTTON (Layout, 31);
859         MAKE_WHITE_BUTTON (OctaveUp, 55);
860         MAKE_WHITE_BUTTON (PageRight, 63);
861         MAKE_WHITE_BUTTON (OctaveDown, 54);
862         MAKE_WHITE_BUTTON (PageLeft, 62);
863         MAKE_WHITE_BUTTON_PRESS_RELEASE (Shift, 49, &Push2::button_shift_press, &Push2::button_shift_release);
864         MAKE_WHITE_BUTTON (Select, 48);
865 }
866
867 void
868 Push2::thread_init ()
869 {
870         struct sched_param rtparam;
871
872         pthread_set_name (event_loop_name().c_str());
873
874         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
875         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
876
877         memset (&rtparam, 0, sizeof (rtparam));
878         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
879
880         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
881                 // do we care? not particularly.
882         }
883 }
884
885 void
886 Push2::connect_session_signals()
887 {
888         // receive routes added
889         //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
890         // receive VCAs added
891         //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
892
893         // receive record state toggled
894         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
895         // receive transport state changed
896         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
897         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
898         // receive punch-in and punch-out
899         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
900         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
901         // receive rude solo changed
902         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
903 }
904
905 void
906 Push2::notify_record_state_changed ()
907 {
908         IDButtonMap::iterator b = id_button_map.find (RecordEnable);
909
910         if (b == id_button_map.end()) {
911                 return;
912         }
913
914         switch (session->record_status ()) {
915         case Session::Disabled:
916                 b->second->set_color (LED::White);
917                 b->second->set_state (LED::NoTransition);
918                 break;
919         case Session::Enabled:
920                 b->second->set_color (LED::Red);
921                 b->second->set_state (LED::Blinking4th);
922                 break;
923         case Session::Recording:
924                 b->second->set_color (LED::Red);
925                 b->second->set_state (LED::OneShot24th);
926                 break;
927         }
928
929         write (b->second->state_msg());
930 }
931
932 void
933 Push2::notify_transport_state_changed ()
934 {
935         Button* b = id_button_map[Play];
936
937         if (session->transport_rolling()) {
938                 b->set_state (LED::OneShot24th);
939                 b->set_color (LED::Green);
940         } else {
941
942                 /* disable any blink on FixedLength from pending edit range op */
943                 Button* fl = id_button_map[FixedLength];
944
945                 fl->set_color (LED::Black);
946                 fl->set_state (LED::NoTransition);
947                 write (fl->state_msg());
948
949                 b->set_color (LED::White);
950                 b->set_state (LED::NoTransition);
951         }
952
953         write (b->state_msg());
954 }
955
956 void
957 Push2::notify_loop_state_changed ()
958 {
959 }
960
961 void
962 Push2::notify_parameter_changed (std::string param)
963 {
964         IDButtonMap::iterator b;
965
966         if (param == "clicking") {
967                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
968                         return;
969                 }
970                 if (Config->get_clicking()) {
971                         b->second->set_state (LED::Blinking4th);
972                         b->second->set_color (LED::White);
973                 } else {
974                         b->second->set_color (LED::White);
975                         b->second->set_state (LED::NoTransition);
976                 }
977                 write (b->second->state_msg ());
978         }
979 }
980
981 void
982 Push2::notify_solo_active_changed (bool yn)
983 {
984         IDButtonMap::iterator b = id_button_map.find (Solo);
985
986         if (b == id_button_map.end()) {
987                 return;
988         }
989
990         if (yn) {
991                 b->second->set_state (LED::Blinking4th);
992                 b->second->set_color (LED::Red);
993         } else {
994                 b->second->set_state (LED::NoTransition);
995                 b->second->set_color (LED::White);
996         }
997
998         write (b->second->state_msg());
999 }
1000
1001 XMLNode&
1002 Push2::get_state()
1003 {
1004         XMLNode& node (ControlProtocol::get_state());
1005         XMLNode* child;
1006
1007         child = new XMLNode (X_("Input"));
1008         child->add_child_nocopy (_async_in->get_state());
1009         node.add_child_nocopy (*child);
1010         child = new XMLNode (X_("Output"));
1011         child->add_child_nocopy (_async_out->get_state());
1012         node.add_child_nocopy (*child);
1013
1014         return node;
1015 }
1016
1017 int
1018 Push2::set_state (const XMLNode & node, int version)
1019 {
1020         DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
1021
1022         int retval = 0;
1023
1024         if (ControlProtocol::set_state (node, version)) {
1025                 return -1;
1026         }
1027
1028         XMLNode* child;
1029
1030         if ((child = node.child (X_("Input"))) != 0) {
1031                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
1032                 if (portnode) {
1033                         _async_in->set_state (*portnode, version);
1034                 }
1035         }
1036
1037         if ((child = node.child (X_("Output"))) != 0) {
1038                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
1039                 if (portnode) {
1040                         _async_out->set_state (*portnode, version);
1041                 }
1042         }
1043
1044         return retval;
1045 }
1046
1047 void
1048 Push2::switch_bank (uint32_t base)
1049 {
1050         if (!session) {
1051                 return;
1052         }
1053
1054         stripable_connections.drop_connections ();
1055
1056         /* try to get the first stripable for the requested bank */
1057
1058         stripable[0] = session->get_nth_stripable (base+0);
1059
1060         if (!stripable[0]) {
1061                 return;
1062         }
1063
1064         /* at least one stripable in this bank */
1065         bank_start = base;
1066
1067         stripable[1] = session->get_nth_stripable (base+1);
1068         stripable[2] = session->get_nth_stripable (base+2);
1069         stripable[3] = session->get_nth_stripable (base+3);
1070         stripable[4] = session->get_nth_stripable (base+4);
1071         stripable[5] = session->get_nth_stripable (base+5);
1072         stripable[6] = session->get_nth_stripable (base+6);
1073         stripable[7] = session->get_nth_stripable (base+7);
1074
1075         for (int n = 0; n < 8; ++n) {
1076                 if (!stripable[n]) {
1077                         continue;
1078                 }
1079
1080                 /* stripable goes away? refill the bank, starting at the same point */
1081
1082                 stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::switch_bank, this, bank_start), this);
1083                 boost::shared_ptr<AutomationControl> sc = stripable[n]->solo_control();
1084                 if (sc) {
1085                         sc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::solo_change, this, n), this);
1086                 }
1087
1088                 boost::shared_ptr<AutomationControl> mc = stripable[n]->mute_control();
1089                 if (mc) {
1090                         mc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::mute_change, this, n), this);
1091                 }
1092
1093                 solo_change (n);
1094                 mute_change (n);
1095
1096         }
1097
1098         /* master cannot be removed, so no need to connect to going-away signal */
1099         master = session->master_out ();
1100 }
1101
1102 void
1103 Push2::solo_change (int n)
1104 {
1105         ButtonID bid;
1106
1107         switch (n) {
1108         case 0:
1109                 bid = Upper1;
1110                 break;
1111         case 1:
1112                 bid = Upper2;
1113                 break;
1114         case 2:
1115                 bid = Upper3;
1116                 break;
1117         case 3:
1118                 bid = Upper4;
1119                 break;
1120         case 4:
1121                 bid = Upper5;
1122                 break;
1123         case 5:
1124                 bid = Upper6;
1125                 break;
1126         case 6:
1127                 bid = Upper7;
1128                 break;
1129         case 7:
1130                 bid = Upper8;
1131                 break;
1132         default:
1133                 return;
1134         }
1135
1136         boost::shared_ptr<AutomationControl> ac = stripable[n]->solo_control ();
1137         if (!ac) {
1138                 return;
1139         }
1140
1141         Button* b = id_button_map[bid];
1142         if (ac->get_value()) {
1143                 b->set_color (LED::Red);
1144         } else {
1145                 b->set_color (LED::Black);
1146         }
1147         b->set_state (LED::OneShot24th);
1148         write (b->state_msg());
1149 }
1150
1151 void
1152 Push2::mute_change (int n)
1153 {
1154         ButtonID bid;
1155
1156         switch (n) {
1157         case 0:
1158                 bid = Lower1;
1159                 break;
1160         case 1:
1161                 bid = Lower2;
1162                 break;
1163         case 2:
1164                 bid = Lower3;
1165                 break;
1166         case 3:
1167                 bid = Lower4;
1168                 break;
1169         case 4:
1170                 bid = Lower5;
1171                 break;
1172         case 5:
1173                 bid = Lower6;
1174                 break;
1175         case 6:
1176                 bid = Lower7;
1177                 break;
1178         case 7:
1179                 bid = Lower8;
1180                 break;
1181         default:
1182                 return;
1183         }
1184
1185         boost::shared_ptr<AutomationControl> ac = stripable[n]->mute_control ();
1186         if (!ac) {
1187                 return;
1188         }
1189
1190         Button* b = id_button_map[bid];
1191
1192         if (ac->get_value ()) {
1193                 b->set_color (LED::Blue);
1194         } else {
1195                 b->set_color (LED::Black);
1196         }
1197         b->set_state (LED::OneShot24th);
1198         write (b->state_msg());
1199 }
1200
1201 void
1202 Push2::strip_vpot (int n, int delta)
1203 {
1204         if (stripable[n]) {
1205                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1206                 if (ac) {
1207                         ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1208                 }
1209         }
1210 }
1211
1212 void
1213 Push2::strip_vpot_touch (int n, bool touching)
1214 {
1215         if (stripable[n]) {
1216                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1217                 if (ac) {
1218                         if (touching) {
1219                                 ac->start_touch (session->audible_frame());
1220                         } else {
1221                                 ac->stop_touch (true, session->audible_frame());
1222                         }
1223                 }
1224         }
1225 }
1226
1227 void
1228 Push2::other_vpot (int n, int delta)
1229 {
1230         switch (n) {
1231         case 0:
1232                 break;
1233         case 1:
1234                 break;
1235         case 2:
1236                 /* master gain control */
1237                 if (master) {
1238                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1239                         if (ac) {
1240                                 ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1241                         }
1242                 }
1243                 break;
1244         }
1245 }
1246
1247 void
1248 Push2::other_vpot_touch (int n, bool touching)
1249 {
1250         switch (n) {
1251         case 0:
1252                 break;
1253         case 1:
1254                 break;
1255         case 2:
1256                 if (master) {
1257                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1258                         if (ac) {
1259                                 if (touching) {
1260                                         ac->start_touch (session->audible_frame());
1261                                 } else {
1262                                         ac->stop_touch (true, session->audible_frame());
1263                                 }
1264                         }
1265                 }
1266         }
1267 }