369af80f9e9a1ad7ddc68ff233ab10142d9213a4
[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                 switch_bank (0);
469
470         } else {
471
472                 stop ();
473
474         }
475
476         ControlProtocol::set_active (yn);
477
478         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
479
480         return 0;
481 }
482
483 void
484 Push2::write (const MidiByteArray& data)
485 {
486         cerr << data << endl;
487         /* immediate delivery */
488         _output_port->write (&data[0], data.size(), 0);
489 }
490
491 bool
492 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
493 {
494         if (ioc & ~IO_IN) {
495                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
496                 return false;
497         }
498
499         if (ioc & IO_IN) {
500
501                 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
502
503                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
504                 if (asp) {
505                         asp->clear ();
506                 }
507
508                 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
509                 framepos_t now = AudioEngine::instance()->sample_time();
510                 port->parse (now);
511         }
512
513         return true;
514 }
515
516 bool
517 Push2::periodic ()
518 {
519         return true;
520 }
521
522 void
523 Push2::connect_to_parser ()
524 {
525         DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
526
527         MIDI::Parser* p = _input_port->parser();
528
529         /* Incoming sysex */
530         p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
531         /* V-Pot messages are Controller */
532         p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
533         /* Button messages are NoteOn */
534         p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
535         /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
536         p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
537         /* Fader messages are Pitchbend */
538         p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
539 }
540
541 void
542 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
543 {
544         cerr << "sysex, " << sz << " bytes\n";
545 }
546
547 void
548 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
549 {
550         CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
551         if (b != cc_button_map.end()) {
552                 if (ev->value == 0) {
553                         (this->*b->second->release_method)();
554                 } else {
555                         (this->*b->second->press_method)();
556                 }
557         }
558 }
559
560 void
561 Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
562 {
563         cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
564 }
565
566 void
567 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
568 {
569         cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
570 }
571
572 void
573 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
574 {
575         cerr << "pitchbend @ " << pb << endl;
576 }
577
578 void
579 Push2::build_maps ()
580 {
581         /* Pads */
582
583         Pad* pad;
584
585 #define MAKE_PAD(x,y,nn) \
586         pad = new Pad ((x), (y), (nn)); \
587         nn_pad_map.insert (make_pair (pad->extra(), pad)); \
588         coord_pad_map.insert (make_pair (pad->coord(), pad));
589
590         MAKE_PAD (0, 1, 93);
591         MAKE_PAD (0, 2, 94);
592         MAKE_PAD (0, 3, 95);
593         MAKE_PAD (0, 4, 96);
594         MAKE_PAD (0, 5, 97);
595         MAKE_PAD (0, 6, 98);
596         MAKE_PAD (0, 7, 90);
597         MAKE_PAD (1, 0, 84);
598         MAKE_PAD (1, 1, 85);
599         MAKE_PAD (1, 2, 86);
600         MAKE_PAD (1, 3, 87);
601         MAKE_PAD (1, 4, 88);
602         MAKE_PAD (1, 5, 89);
603         MAKE_PAD (1, 6, 90);
604         MAKE_PAD (1, 7, 91);
605         MAKE_PAD (2, 0, 76);
606         MAKE_PAD (2, 1, 77);
607         MAKE_PAD (2, 2, 78);
608         MAKE_PAD (2, 3, 79);
609         MAKE_PAD (2, 4, 80);
610         MAKE_PAD (2, 5, 81);
611         MAKE_PAD (2, 6, 82);
612         MAKE_PAD (2, 7, 83);
613         MAKE_PAD (3, 0, 68);
614         MAKE_PAD (3, 1, 69);
615         MAKE_PAD (3, 2, 70);
616         MAKE_PAD (3, 3, 71);
617         MAKE_PAD (3, 4, 72);
618         MAKE_PAD (3, 5, 73);
619         MAKE_PAD (3, 6, 74);
620         MAKE_PAD (3, 7, 75);
621         MAKE_PAD (4, 0, 60);
622         MAKE_PAD (4, 1, 61);
623         MAKE_PAD (4, 2, 62);
624         MAKE_PAD (4, 3, 63);
625         MAKE_PAD (4, 4, 64);
626         MAKE_PAD (4, 5, 65);
627         MAKE_PAD (4, 6, 66);
628         MAKE_PAD (4, 7, 67);
629         MAKE_PAD (5, 0, 52);
630         MAKE_PAD (5, 1, 53);
631         MAKE_PAD (5, 2, 54);
632         MAKE_PAD (5, 3, 56);
633         MAKE_PAD (5, 4, 56);
634         MAKE_PAD (5, 5, 57);
635         MAKE_PAD (5, 6, 58);
636         MAKE_PAD (5, 7, 59);
637         MAKE_PAD (6, 0, 44);
638         MAKE_PAD (6, 1, 45);
639         MAKE_PAD (6, 2, 46);
640         MAKE_PAD (6, 3, 47);
641         MAKE_PAD (6, 4, 48);
642         MAKE_PAD (6, 5, 49);
643         MAKE_PAD (6, 6, 50);
644         MAKE_PAD (6, 7, 51);
645         MAKE_PAD (7, 0, 36);
646         MAKE_PAD (7, 1, 37);
647         MAKE_PAD (7, 2, 38);
648         MAKE_PAD (7, 3, 39);
649         MAKE_PAD (7, 4, 40);
650         MAKE_PAD (7, 5, 41);
651         MAKE_PAD (7, 6, 42);
652         MAKE_PAD (7, 7, 43);
653
654         /* Now color buttons */
655
656         Button *button;
657
658 #define MAKE_COLOR_BUTTON(i,cc) \
659         button = new ColorButton ((i), (cc)); \
660         cc_button_map.insert (make_pair (button->controller_number(), button)); \
661         id_button_map.insert (make_pair (button->id, button));
662 #define MAKE_COLOR_BUTTON_PRESS(i,cc,p)\
663         button = new ColorButton ((i), (cc), (p)); \
664         cc_button_map.insert (make_pair (button->controller_number(), button)); \
665         id_button_map.insert (make_pair (button->id, button))
666
667         MAKE_COLOR_BUTTON_PRESS (Upper1, 102, &Push2::button_upper_1);
668         MAKE_COLOR_BUTTON_PRESS (Upper2, 103, &Push2::button_upper_2);
669         MAKE_COLOR_BUTTON_PRESS (Upper3, 104, &Push2::button_upper_3);
670         MAKE_COLOR_BUTTON_PRESS (Upper4, 105, &Push2::button_upper_4);
671         MAKE_COLOR_BUTTON_PRESS (Upper5, 106, &Push2::button_upper_5);
672         MAKE_COLOR_BUTTON_PRESS (Upper6, 107, &Push2::button_upper_6);
673         MAKE_COLOR_BUTTON_PRESS (Upper7, 108, &Push2::button_upper_7);
674         MAKE_COLOR_BUTTON_PRESS (Upper8, 109, &Push2::button_upper_8);
675         MAKE_COLOR_BUTTON_PRESS (Lower1, 20, &Push2::button_lower_1);
676         MAKE_COLOR_BUTTON_PRESS (Lower2, 21, &Push2::button_lower_2);
677         MAKE_COLOR_BUTTON_PRESS (Lower3, 22, &Push2::button_lower_3);
678         MAKE_COLOR_BUTTON_PRESS (Lower4, 23, &Push2::button_lower_4);
679         MAKE_COLOR_BUTTON_PRESS (Lower5, 24, &Push2::button_lower_5);
680         MAKE_COLOR_BUTTON_PRESS (Lower6, 25, &Push2::button_lower_6);
681         MAKE_COLOR_BUTTON_PRESS (Lower7, 26, &Push2::button_lower_7);
682         MAKE_COLOR_BUTTON_PRESS (Lower8, 27, &Push2::button_lower_8);
683         MAKE_COLOR_BUTTON (Master, 28);
684         MAKE_COLOR_BUTTON (Mute, 60);
685         MAKE_COLOR_BUTTON_PRESS (Solo, 61, &Push2::button_solo);
686         MAKE_COLOR_BUTTON (Stop, 29);
687         MAKE_COLOR_BUTTON_PRESS (Fwd32ndT, 43, &Push2::button_fwd32t);
688         MAKE_COLOR_BUTTON_PRESS (Fwd32nd,42 , &Push2::button_fwd32);
689         MAKE_COLOR_BUTTON_PRESS (Fwd16thT, 41, &Push2::button_fwd16t);
690         MAKE_COLOR_BUTTON_PRESS (Fwd16th, 40, &Push2::button_fwd16);
691         MAKE_COLOR_BUTTON_PRESS (Fwd8thT, 39 , &Push2::button_fwd8t);
692         MAKE_COLOR_BUTTON_PRESS (Fwd8th, 38, &Push2::button_fwd8);
693         MAKE_COLOR_BUTTON_PRESS (Fwd4trT, 37, &Push2::button_fwd4t);
694         MAKE_COLOR_BUTTON_PRESS (Fwd4tr, 36, &Push2::button_fwd4);
695         MAKE_COLOR_BUTTON (Automate, 89);
696         MAKE_COLOR_BUTTON_PRESS (RecordEnable, 86, &Push2::button_recenable);
697         MAKE_COLOR_BUTTON_PRESS (Play, 85, &Push2::button_play);
698
699 #define MAKE_WHITE_BUTTON(i,cc)\
700         button = new WhiteButton ((i), (cc)); \
701         cc_button_map.insert (make_pair (button->controller_number(), button)); \
702         id_button_map.insert (make_pair (button->id, button))
703 #define MAKE_WHITE_BUTTON_PRESS(i,cc,p)\
704         button = new WhiteButton ((i), (cc), (p)); \
705         cc_button_map.insert (make_pair (button->controller_number(), button)); \
706         id_button_map.insert (make_pair (button->id, button))
707 #define MAKE_WHITE_BUTTON_PRESS_RELEASE(i,cc,p,r)                                \
708         button = new WhiteButton ((i), (cc), (p), (r)); \
709         cc_button_map.insert (make_pair (button->controller_number(), button)); \
710         id_button_map.insert (make_pair (button->id, button))
711
712         MAKE_WHITE_BUTTON (TapTempo, 3);
713         MAKE_WHITE_BUTTON_PRESS (Metronome, 9, &Push2::button_metronome);
714         MAKE_WHITE_BUTTON (Setup, 30);
715         MAKE_WHITE_BUTTON (User, 59);
716         MAKE_WHITE_BUTTON (Delete, 118);
717         MAKE_WHITE_BUTTON (AddDevice, 52);
718         MAKE_WHITE_BUTTON (Device, 110);
719         MAKE_WHITE_BUTTON (Mix, 112);
720         MAKE_WHITE_BUTTON_PRESS (Undo, 119, &Push2::button_undo);
721         MAKE_WHITE_BUTTON (AddTrack, 53);
722         MAKE_WHITE_BUTTON_PRESS (Browse, 111, &Push2::button_browse);
723         MAKE_WHITE_BUTTON_PRESS (Clip, 113, &Push2::button_clip);
724         MAKE_WHITE_BUTTON (Convert, 35);
725         MAKE_WHITE_BUTTON (DoubleLoop, 117);
726         MAKE_WHITE_BUTTON (Quantize, 116);
727         MAKE_WHITE_BUTTON (Duplicate, 88);
728         MAKE_WHITE_BUTTON_PRESS (New, 87, &Push2::button_new);
729         MAKE_WHITE_BUTTON_PRESS (FixedLength, 90, &Push2::button_fixed_length);
730         MAKE_WHITE_BUTTON_PRESS (Up, 46, &Push2::button_up);
731         MAKE_WHITE_BUTTON_PRESS (Right, 45, &Push2::button_right);
732         MAKE_WHITE_BUTTON_PRESS (Down, 47, &Push2::button_down);
733         MAKE_WHITE_BUTTON_PRESS (Left, 44, &Push2::button_left);
734         MAKE_WHITE_BUTTON_PRESS (Repeat, 56, &Push2::button_repeat);
735         MAKE_WHITE_BUTTON (Accent, 57);
736         MAKE_WHITE_BUTTON (Scale, 58);
737         MAKE_WHITE_BUTTON (Layout, 31);
738         MAKE_WHITE_BUTTON (Note, 50);
739         MAKE_WHITE_BUTTON (Session, 51);
740         MAKE_WHITE_BUTTON (Layout, 31);
741         MAKE_WHITE_BUTTON (OctaveUp, 55);
742         MAKE_WHITE_BUTTON (PageRight, 63);
743         MAKE_WHITE_BUTTON (OctaveDown, 54);
744         MAKE_WHITE_BUTTON (PageLeft, 62);
745         MAKE_WHITE_BUTTON_PRESS_RELEASE (Shift, 49, &Push2::button_shift_press, &Push2::button_shift_release);
746         MAKE_WHITE_BUTTON (Select, 48);
747 }
748
749 void
750 Push2::thread_init ()
751 {
752         struct sched_param rtparam;
753
754         pthread_set_name (event_loop_name().c_str());
755
756         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
757         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
758
759         memset (&rtparam, 0, sizeof (rtparam));
760         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
761
762         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
763                 // do we care? not particularly.
764         }
765 }
766
767 void
768 Push2::connect_session_signals()
769 {
770         // receive routes added
771         //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
772         // receive VCAs added
773         //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
774
775         // receive record state toggled
776         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
777         // receive transport state changed
778         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
779         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
780         // receive punch-in and punch-out
781         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
782         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
783         // receive rude solo changed
784         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
785 }
786
787 void
788 Push2::notify_record_state_changed ()
789 {
790         IDButtonMap::iterator b = id_button_map.find (RecordEnable);
791
792         if (b == id_button_map.end()) {
793                 return;
794         }
795
796         switch (session->record_status ()) {
797         case Session::Disabled:
798                 b->second->set_color (LED::White);
799                 b->second->set_state (LED::NoTransition);
800                 break;
801         case Session::Enabled:
802                 b->second->set_color (LED::Red);
803                 b->second->set_state (LED::Blinking4th);
804                 break;
805         case Session::Recording:
806                 b->second->set_color (LED::Red);
807                 b->second->set_state (LED::OneShot24th);
808                 break;
809         }
810
811         write (b->second->state_msg());
812 }
813
814 void
815 Push2::notify_transport_state_changed ()
816 {
817         Button* b = id_button_map[Play];
818
819         if (session->transport_rolling()) {
820                 b->set_state (LED::OneShot24th);
821                 b->set_color (LED::Green);
822         } else {
823
824                 /* disable any blink on FixedLength from pending edit range op */
825                 Button* fl = id_button_map[FixedLength];
826
827                 fl->set_color (LED::Black);
828                 fl->set_state (LED::NoTransition);
829                 write (fl->state_msg());
830
831                 b->set_color (LED::White);
832                 b->set_state (LED::NoTransition);
833         }
834
835         write (b->state_msg());
836 }
837
838 void
839 Push2::notify_loop_state_changed ()
840 {
841 }
842
843 void
844 Push2::notify_parameter_changed (std::string param)
845 {
846         IDButtonMap::iterator b;
847
848         if (param == "clicking") {
849                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
850                         return;
851                 }
852                 if (Config->get_clicking()) {
853                         b->second->set_state (LED::Blinking4th);
854                         b->second->set_color (LED::White);
855                 } else {
856                         b->second->set_color (LED::White);
857                         b->second->set_state (LED::NoTransition);
858                 }
859                 write (b->second->state_msg ());
860         }
861 }
862
863 void
864 Push2::notify_solo_active_changed (bool yn)
865 {
866         IDButtonMap::iterator b = id_button_map.find (Solo);
867
868         if (b == id_button_map.end()) {
869                 return;
870         }
871
872         if (yn) {
873                 b->second->set_state (LED::Blinking4th);
874                 b->second->set_color (LED::Red);
875         } else {
876                 b->second->set_state (LED::NoTransition);
877                 b->second->set_color (LED::White);
878         }
879
880         write (b->second->state_msg());
881 }
882
883 XMLNode&
884 Push2::get_state()
885 {
886         XMLNode& node (ControlProtocol::get_state());
887         XMLNode* child;
888
889         child = new XMLNode (X_("Input"));
890         child->add_child_nocopy (_async_in->get_state());
891         node.add_child_nocopy (*child);
892         child = new XMLNode (X_("Output"));
893         child->add_child_nocopy (_async_out->get_state());
894         node.add_child_nocopy (*child);
895
896         return node;
897 }
898
899 int
900 Push2::set_state (const XMLNode & node, int version)
901 {
902         DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
903
904         int retval = 0;
905
906         if (ControlProtocol::set_state (node, version)) {
907                 return -1;
908         }
909
910         XMLNode* child;
911
912         if ((child = node.child (X_("Input"))) != 0) {
913                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
914                 if (portnode) {
915                         _async_in->set_state (*portnode, version);
916                 }
917         }
918
919         if ((child = node.child (X_("Output"))) != 0) {
920                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
921                 if (portnode) {
922                         _async_out->set_state (*portnode, version);
923                 }
924         }
925
926         return retval;
927 }
928
929 void
930 Push2::switch_bank (uint32_t base)
931 {
932         if (!session) {
933                 return;
934         }
935
936         stripable_connections.drop_connections ();
937
938         /* try to get the first stripable for the requested bank */
939
940         stripable[0] = session->get_nth_stripable (base+0);
941
942         if (!stripable[0]) {
943                 return;
944         }
945
946         /* at least one stripable in this bank */
947         bank_start = base;
948
949         stripable[1] = session->get_nth_stripable (base+1);
950         stripable[2] = session->get_nth_stripable (base+2);
951         stripable[3] = session->get_nth_stripable (base+3);
952         stripable[4] = session->get_nth_stripable (base+4);
953         stripable[5] = session->get_nth_stripable (base+5);
954         stripable[6] = session->get_nth_stripable (base+6);
955         stripable[7] = session->get_nth_stripable (base+7);
956
957         for (int n = 0; n < 8; ++n) {
958                 if (!stripable[n]) {
959                         continue;
960                 }
961
962                 /* stripable goes away? refill the bank, starting at the same point */
963
964                 stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::switch_bank, this, bank_start), this);
965                 boost::shared_ptr<AutomationControl> sc = stripable[n]->solo_control();
966                 if (sc) {
967                         sc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::solo_change, this, n), this);
968                 }
969
970                 boost::shared_ptr<AutomationControl> mc = stripable[n]->mute_control();
971                 if (mc) {
972                         mc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::mute_change, this, n), this);
973                 }
974
975                 solo_change (n);
976                 mute_change (n);
977
978         }
979 }
980
981 void
982 Push2::solo_change (int n)
983 {
984         ButtonID bid;
985
986         switch (n) {
987         case 0:
988                 bid = Upper1;
989                 break;
990         case 1:
991                 bid = Upper2;
992                 break;
993         case 2:
994                 bid = Upper3;
995                 break;
996         case 3:
997                 bid = Upper4;
998                 break;
999         case 4:
1000                 bid = Upper5;
1001                 break;
1002         case 5:
1003                 bid = Upper6;
1004                 break;
1005         case 6:
1006                 bid = Upper7;
1007                 break;
1008         case 7:
1009                 bid = Upper8;
1010                 break;
1011         default:
1012                 return;
1013         }
1014
1015         boost::shared_ptr<AutomationControl> ac = stripable[n]->solo_control ();
1016         if (!ac) {
1017                 return;
1018         }
1019
1020         Button* b = id_button_map[bid];
1021         if (ac->get_value()) {
1022                 b->set_color (LED::Red);
1023         } else {
1024                 b->set_color (LED::Black);
1025         }
1026         b->set_state (LED::OneShot24th);
1027         write (b->state_msg());
1028 }
1029
1030 void
1031 Push2::mute_change (int n)
1032 {
1033         ButtonID bid;
1034
1035         switch (n) {
1036         case 0:
1037                 bid = Lower1;
1038                 break;
1039         case 1:
1040                 bid = Lower2;
1041                 break;
1042         case 2:
1043                 bid = Lower3;
1044                 break;
1045         case 3:
1046                 bid = Lower4;
1047                 break;
1048         case 4:
1049                 bid = Lower5;
1050                 break;
1051         case 5:
1052                 bid = Lower6;
1053                 break;
1054         case 6:
1055                 bid = Lower7;
1056                 break;
1057         case 7:
1058                 bid = Lower8;
1059                 break;
1060         default:
1061                 return;
1062         }
1063
1064         boost::shared_ptr<AutomationControl> ac = stripable[n]->mute_control ();
1065         if (!ac) {
1066                 return;
1067         }
1068
1069         Button* b = id_button_map[bid];
1070
1071         if (ac->get_value ()) {
1072                 b->set_color (LED::Blue);
1073         } else {
1074                 b->set_color (LED::Black);
1075         }
1076         b->set_state (LED::OneShot24th);
1077         write (b->state_msg());
1078 }