2 Copyright (C) 2016 Paul Davis
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.
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.
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.
19 #include <cairomm/context.h>
20 #include <cairomm/surface.h>
21 #include <pangomm/layout.h>
23 #include "pbd/compose.h"
24 #include "pbd/debug.h"
25 #include "pbd/failed_constructor.h"
27 #include "midi++/parser.h"
29 #include "ardour/async_midi_port.h"
30 #include "ardour/audioengine.h"
31 #include "ardour/debug.h"
32 #include "ardour/midiport_manager.h"
33 #include "ardour/session.h"
36 using namespace ARDOUR;
40 using namespace ArdourSurface;
44 #include "pbd/abstract_ui.cc" // instantiate template
46 const int Push2::cols = 960;
47 const int Push2::rows = 160;
48 const int Push2::pixels_per_row = 1024;
50 #define ABLETON 0x2982
53 Push2::Push2 (ARDOUR::Session& s)
54 : ControlProtocol (s, string (X_("Ableton Push 2")))
55 , AbstractUI<Push2Request> (name())
58 , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
61 throw failed_constructor ();
82 if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
86 if ((err = libusb_claim_interface (handle, 0x00))) {
90 device_frame_buffer[0] = new uint16_t[rows*pixels_per_row];
91 device_frame_buffer[1] = new uint16_t[rows*pixels_per_row];
93 memset (device_frame_buffer[0], 0, sizeof (uint16_t) * rows * pixels_per_row);
94 memset (device_frame_buffer[1], 0, sizeof (uint16_t) * rows * pixels_per_row);
96 frame_header[0] = 0xef;
97 frame_header[1] = 0xcd;
98 frame_header[2] = 0xab;
99 frame_header[3] = 0x89;
100 memset (&frame_header[4], 0, 12);
104 _async_in = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in"), true);
105 _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out"), true);
107 if (_async_in == 0 || _async_out == 0) {
111 _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
112 _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
114 connect_to_parser ();
122 AudioEngine::instance()->unregister_port (_async_in);
123 AudioEngine::instance()->unregister_port (_async_out);
125 _async_in.reset ((ARDOUR::Port*) 0);
126 _async_out.reset ((ARDOUR::Port*) 0);
130 vblank_connection.disconnect ();
131 periodic_connection.disconnect ();
132 session_connections.drop_connections ();
135 libusb_release_interface (handle, 0x00);
136 libusb_close (handle);
140 delete [] device_frame_buffer[0];
141 device_frame_buffer[0] = 0;
143 delete [] device_frame_buffer[1];
144 device_frame_buffer[1] = 0;
152 libusb_device_handle *h;
155 if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
156 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
161 DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
166 Push2::request_factory (uint32_t num_requests)
168 /* AbstractUI<T>::request_buffer_factory() is a template method only
169 instantiated in this source module. To provide something visible for
170 use in the interface/descriptor, we have this static method that is
173 return request_buffer_factory (num_requests);
177 Push2::do_request (Push2Request * req)
179 DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
180 if (req->type == CallSlot) {
182 call_slot (MISSING_INVALIDATOR, req->the_slot);
184 } else if (req->type == Quit) {
198 /** render host-side frame buffer (a Cairo ImageSurface) to the current
199 * device-side frame buffer. The device frame buffer will be pushed to the
200 * device on the next call to vblank()
206 /* ensure that all drawing has been done before we fetch pixel data */
208 frame_buffer->flush ();
210 const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
211 const uint8_t* data = frame_buffer->get_data ();
213 /* fill frame buffer (320kB) */
215 Glib::Threads::Mutex::Lock lm (fb_lock);
217 uint16_t* fb = (uint16_t*) device_frame_buffer[device_buffer];
219 for (int row = 0; row < rows; ++row) {
221 const uint8_t* dp = data + row * stride;
223 for (int col = 0; col < cols; ++col) {
225 /* fetch r, g, b (range 0..255). Ignore alpha */
227 const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
228 const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
229 const int b = *((const uint32_t*)dp) & 0xff;
231 /* convert to 5 bits, 6 bits, 5 bits, respectively */
232 /* generate 16 bit BGB565 value */
234 *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
239 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
243 fb += 64; /* 128 bytes = 64 int16_t */
246 /* swap buffers (under lock protection) */
247 // device_buffer = (device_buffer ? 0 : 1);
256 const int timeout_msecs = 1000;
259 if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
264 Glib::Threads::Mutex::Lock lm (fb_lock);
266 if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer[device_buffer] , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
275 Push2::set_active (bool yn)
277 DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
279 if (yn == active()) {
285 /* start event loop */
290 DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
295 /* Connect input port to event loop */
299 asp = dynamic_cast<AsyncMIDIPort*> (_input_port);
300 asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port));
301 asp->xthread().attach (main_loop()->get_context());
303 connect_session_signals ();
307 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (frame_buffer);
308 Glib::RefPtr<Pango::Layout> layout = Pango::Layout::create (context);
310 layout->set_text ("hello, Ardour");
311 Pango::FontDescription fd ("Sans Bold 12");
312 layout->set_font_description (fd);
314 context->set_source_rgb (0.0, 1.0, 1.0);
315 context->rectangle (0, 0, 960, 160);
317 context->set_source_rgb (0.0, 0.0, 0.0);
318 context->rectangle (50, 50, 860, 60);
320 context->move_to (60, 60);
321 context->set_source_rgb ((random()%255) / 255.0, (random()%255) / 255.0, (random()%255) / 255.0);
322 layout->update_from_cairo_context (context);
323 layout->show_in_cairo_context (context);
327 /* set up periodic task used to push a frame buffer to the
328 * device (25fps). The device can handle 60fps, but we don't
329 * need that frame rate.
332 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
333 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
334 vblank_timeout->attach (main_loop()->get_context());
337 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (1000); // milliseconds
338 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
339 periodic_timeout->attach (main_loop()->get_context());
347 ControlProtocol::set_active (yn);
349 DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
355 Push2::write (const MidiByteArray& data)
357 cerr << data << endl;
358 /* immediate delivery */
359 _output_port->write (&data[0], data.size(), 0);
363 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
366 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
372 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on %1\n", port->name()));
374 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
379 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
380 framepos_t now = AudioEngine::instance()->sample_time();
394 Push2::connect_to_parser ()
396 DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
398 MIDI::Parser* p = _input_port->parser();
401 p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
402 /* V-Pot messages are Controller */
403 p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
404 /* Button messages are NoteOn */
405 p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
406 /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
407 p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
408 /* Fader messages are Pitchbend */
409 p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
413 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
415 cerr << "sysex, " << sz << " bytes\n";
419 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
421 CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
422 if (b != cc_button_map.end()) {
423 if (ev->value == 0) {
424 (this->*b->second->release_method)();
426 (this->*b->second->press_method)();
432 Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
434 cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
438 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
440 cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
444 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
446 cerr << "pitchbend @ " << pb << endl;
456 #define MAKE_PAD(x,y,nn) \
457 pad = new Pad ((x), (y), (nn)); \
458 nn_pad_map.insert (make_pair (pad->extra(), pad)); \
459 coord_pad_map.insert (make_pair (pad->coord(), pad));
525 /* Now color buttons */
529 #define MAKE_COLOR_BUTTON(i,cc) \
530 button = new ColorButton ((i), (cc)); \
531 cc_button_map.insert (make_pair (button->controller_number(), button)); \
532 id_button_map.insert (make_pair (button->id, button));
533 #define MAKE_COLOR_BUTTON_PRESS(i,cc,p)\
534 button = new ColorButton ((i), (cc), (p)); \
535 cc_button_map.insert (make_pair (button->controller_number(), button)); \
536 id_button_map.insert (make_pair (button->id, button))
538 MAKE_COLOR_BUTTON (Upper1, 102);
539 MAKE_COLOR_BUTTON (Upper2, 103);
540 MAKE_COLOR_BUTTON (Upper3, 104);
541 MAKE_COLOR_BUTTON (Upper4, 105);
542 MAKE_COLOR_BUTTON (Upper5, 106);
543 MAKE_COLOR_BUTTON (Upper6, 107);
544 MAKE_COLOR_BUTTON (Upper7, 108);
545 MAKE_COLOR_BUTTON (Upper8, 109);
546 MAKE_COLOR_BUTTON (Lower1, 21);
547 MAKE_COLOR_BUTTON (Lower2, 22);
548 MAKE_COLOR_BUTTON (Lower3, 23);
549 MAKE_COLOR_BUTTON (Lower4, 24);
550 MAKE_COLOR_BUTTON (Lower5, 25);
551 MAKE_COLOR_BUTTON (Lower6, 26);
552 MAKE_COLOR_BUTTON (Lower7, 27);
553 MAKE_COLOR_BUTTON (Mute, 60);
554 MAKE_COLOR_BUTTON (Solo, 61);
555 MAKE_COLOR_BUTTON (Stop, 29);
556 MAKE_COLOR_BUTTON (Fwd32ndT, 43);
557 MAKE_COLOR_BUTTON (Fwd32nd,42 );
558 MAKE_COLOR_BUTTON (Fwd16thT, 41);
559 MAKE_COLOR_BUTTON (Fwd16th, 40);
560 MAKE_COLOR_BUTTON (Fwd8thT, 39 );
561 MAKE_COLOR_BUTTON (Fwd8th, 38);
562 MAKE_COLOR_BUTTON (Fwd4trT, 37);
563 MAKE_COLOR_BUTTON (Fwd4tr, 36);
564 MAKE_COLOR_BUTTON (Automate, 89);
565 MAKE_COLOR_BUTTON_PRESS (RecordEnable, 86, &Push2::button_recenable);
566 MAKE_COLOR_BUTTON_PRESS (Play, 85, &Push2::button_play);
568 #define MAKE_WHITE_BUTTON(i,cc)\
569 button = new WhiteButton ((i), (cc)); \
570 cc_button_map.insert (make_pair (button->controller_number(), button)); \
571 id_button_map.insert (make_pair (button->id, button))
572 #define MAKE_WHITE_BUTTON_PRESS(i,cc,p)\
573 button = new WhiteButton ((i), (cc), (p)); \
574 cc_button_map.insert (make_pair (button->controller_number(), button)); \
575 id_button_map.insert (make_pair (button->id, button))
577 MAKE_WHITE_BUTTON (TapTempo, 3);
578 MAKE_WHITE_BUTTON_PRESS (Metronome, 9, &Push2::button_metronome);
579 MAKE_WHITE_BUTTON (Setup, 30);
580 MAKE_WHITE_BUTTON (User, 59);
581 MAKE_WHITE_BUTTON (Delete, 118);
582 MAKE_WHITE_BUTTON (AddDevice, 52);
583 MAKE_WHITE_BUTTON (Device, 110);
584 MAKE_WHITE_BUTTON (Mix, 112);
585 MAKE_WHITE_BUTTON (Undo, 119);
586 MAKE_WHITE_BUTTON (AddTrack, 53);
587 MAKE_WHITE_BUTTON (Browse, 113);
588 MAKE_WHITE_BUTTON (Convert, 35);
589 MAKE_WHITE_BUTTON (DoubleLoop, 117);
590 MAKE_WHITE_BUTTON (Quantize, 116);
591 MAKE_WHITE_BUTTON (Duplicate, 88);
592 MAKE_WHITE_BUTTON (New, 87);
593 MAKE_WHITE_BUTTON (FixedLength, 90);
594 MAKE_WHITE_BUTTON_PRESS (Up, 46, &Push2::button_up);
595 MAKE_WHITE_BUTTON_PRESS (Right, 45, &Push2::button_right);
596 MAKE_WHITE_BUTTON_PRESS (Down, 47, &Push2::button_down);
597 MAKE_WHITE_BUTTON_PRESS (Left, 44, &Push2::button_left);
598 MAKE_WHITE_BUTTON_PRESS (Repeat, 56, &Push2::button_repeat);
599 MAKE_WHITE_BUTTON (Accent, 57);
600 MAKE_WHITE_BUTTON (Scale, 58);
601 MAKE_WHITE_BUTTON (Layout, 31);
602 MAKE_WHITE_BUTTON (OctaveUp, 55);
603 MAKE_WHITE_BUTTON (PageRight, 63);
604 MAKE_WHITE_BUTTON (OctaveDown, 54);
605 MAKE_WHITE_BUTTON (PageLeft, 62);
606 MAKE_WHITE_BUTTON (Shift, 49);
607 MAKE_WHITE_BUTTON (Select, 48);
611 Push2::thread_init ()
613 struct sched_param rtparam;
615 pthread_set_name (event_loop_name().c_str());
617 PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
618 ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
620 memset (&rtparam, 0, sizeof (rtparam));
621 rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
623 if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
624 // do we care? not particularly.
629 Push2::connect_session_signals()
631 // receive routes added
632 //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
633 // receive VCAs added
634 //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
636 // receive record state toggled
637 session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
638 // receive transport state changed
639 session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
640 session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
641 // receive punch-in and punch-out
642 Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
643 session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
644 // receive rude solo changed
645 session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
649 Push2::notify_record_state_changed ()
651 IDButtonMap::iterator b = id_button_map.find (RecordEnable);
653 if (b == id_button_map.end()) {
657 b->second->set_color (LED::Red);
659 switch (session->record_status ()) {
660 case Session::Disabled:
661 b->second->set_state (LED::Off);
663 case Session::Enabled:
664 b->second->set_state (LED::Blinking4th);
666 case Session::Recording:
667 b->second->set_state (LED::OneShot24th);
671 write (b->second->state_msg());
675 Push2::notify_transport_state_changed ()
677 IDButtonMap::iterator b = id_button_map.find (Play);
679 if (b == id_button_map.end()) {
683 if (session->transport_rolling()) {
684 b->second->set_state (LED::OneShot24th);
685 b->second->set_color (LED::Blue);
687 b->second->set_state (LED::Off);
690 write (b->second->state_msg());
694 Push2::notify_loop_state_changed ()
699 Push2::notify_parameter_changed (std::string)
704 Push2::notify_solo_active_changed (bool yn)
706 IDButtonMap::iterator b = id_button_map.find (Solo);
708 if (b == id_button_map.end()) {
713 b->second->set_state (LED::Blinking24th);
715 b->second->set_state (LED::Off);
718 write (b->second->state_msg());
724 XMLNode& node (ControlProtocol::get_state());
727 child = new XMLNode (X_("Input"));
728 child->add_child_nocopy (_async_in->get_state());
729 node.add_child_nocopy (*child);
730 child = new XMLNode (X_("Output"));
731 child->add_child_nocopy (_async_out->get_state());
732 node.add_child_nocopy (*child);
738 Push2::set_state (const XMLNode & node, int version)
740 DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
744 if (ControlProtocol::set_state (node, version)) {
750 if ((child = node.child (X_("Input"))) != 0) {
751 XMLNode* portnode = child->child (Port::state_node_name.c_str());
753 _async_in->set_state (*portnode, version);
757 if ((child = node.child (X_("Output"))) != 0) {
758 XMLNode* portnode = child->child (Port::state_node_name.c_str());
760 _async_out->set_state (*portnode, version);