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