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