4920a18e5e154f2fc74765a7363235ccd62fb8b9
[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/debug.h"
25 #include "pbd/failed_constructor.h"
26
27 #include "ardour/async_midi_port.h"
28 #include "ardour/audioengine.h"
29 #include "ardour/debug.h"
30 #include "ardour/midiport_manager.h"
31 #include "ardour/session.h"
32 #include "push2.h"
33
34 using namespace ARDOUR;
35 using namespace std;
36 using namespace PBD;
37 using namespace Glib;
38 using namespace ArdourSurface;
39
40 #include "i18n.h"
41
42 #include "pbd/abstract_ui.cc" // instantiate template
43
44 const int Push2::cols = 960;
45 const int Push2::rows = 160;
46 const int Push2::pixels_per_row = 1024;
47
48 #define ABLETON 0x2982
49 #define PUSH2   0x1967
50
51 Push2::Push2 (Session& s)
52         : ControlProtocol (s, string (X_("Ableton Push2")))
53         , AbstractUI<Push2Request> (name())
54         , handle (0)
55         , device_buffer (0)
56         , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
57 {
58         build_led_map ();
59 }
60
61 Push2::~Push2 ()
62 {
63         close ();
64 }
65
66 int
67 Push2::open ()
68 {
69         int err;
70
71         if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
72                 return -1;
73         }
74
75         if ((err = libusb_claim_interface (handle, 0x00))) {
76                 return -1;
77         }
78
79         device_frame_buffer[0] = new uint16_t[rows*pixels_per_row];
80         device_frame_buffer[1] = new uint16_t[rows*pixels_per_row];
81
82         memset (device_frame_buffer[0], 0, sizeof (uint16_t) * rows * pixels_per_row);
83         memset (device_frame_buffer[1], 0, sizeof (uint16_t) * rows * pixels_per_row);
84
85         frame_header[0] = 0xef;
86         frame_header[1] = 0xcd;
87         frame_header[2] = 0xab;
88         frame_header[3] = 0x89;
89         memset (&frame_header[4], 0, 12);
90
91         /* setup ports */
92
93         _async_in[0]  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in1"), true);
94         _async_out[0] = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out1"), true);
95
96         if (_async_in[0] == 0 || _async_out[0] == 0) {
97                 return -1;
98         }
99
100         _input_port[0] = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in[0]).get();
101         _output_port[0] = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out[0]).get();
102
103         _async_in[1]  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in2"), true);
104         _async_out[1] = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out2"), true);
105
106         if (_async_in[1] == 0 || _async_out[1] == 0) {
107                 return -1;
108         }
109
110         _input_port[1] = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in[1]).get();
111         _output_port[1] = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out[1]).get();
112
113         AsyncMIDIPort* asp;
114
115         asp = dynamic_cast<AsyncMIDIPort*> (_input_port[0]);
116         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port[0]));
117         asp->xthread().attach (main_loop()->get_context());
118
119         asp = dynamic_cast<AsyncMIDIPort*> (_input_port[1]);
120         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port[1]));
121         asp->xthread().attach (main_loop()->get_context());
122
123         return 0;
124 }
125
126 int
127 Push2::close ()
128 {
129         AudioEngine::instance()->unregister_port (_async_in[0]);
130         AudioEngine::instance()->unregister_port (_async_out[0]);
131         AudioEngine::instance()->unregister_port (_async_in[1]);
132         AudioEngine::instance()->unregister_port (_async_out[1]);
133
134         _async_in[0].reset ((ARDOUR::Port*) 0);
135         _async_out[0].reset ((ARDOUR::Port*) 0);
136         _async_in[1].reset ((ARDOUR::Port*) 0);
137         _async_out[1].reset ((ARDOUR::Port*) 0);
138
139         vblank_connection.disconnect ();
140
141         if (handle) {
142                 libusb_release_interface (handle, 0x00);
143                 libusb_close (handle);
144         }
145
146         delete [] device_frame_buffer[0];
147         device_frame_buffer[0] = 0;
148
149         delete [] device_frame_buffer[1];
150         device_frame_buffer[1] = 0;
151
152         return 0;
153 }
154
155 bool
156 Push2::probe ()
157 {
158         libusb_device_handle *h;
159         libusb_init (NULL);
160
161         if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
162                 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
163                 return false;
164         }
165
166         libusb_close (h);
167         DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
168         return true;
169 }
170
171 void*
172 Push2::request_factory (uint32_t num_requests)
173 {
174         /* AbstractUI<T>::request_buffer_factory() is a template method only
175            instantiated in this source module. To provide something visible for
176            use in the interface/descriptor, we have this static method that is
177            template-free.
178         */
179         return request_buffer_factory (num_requests);
180 }
181
182 void
183 Push2::do_request (Push2Request * req)
184 {
185         DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
186         if (req->type == CallSlot) {
187
188                 call_slot (MISSING_INVALIDATOR, req->the_slot);
189
190         } else if (req->type == Quit) {
191
192                 stop ();
193         }
194 }
195
196 int
197 Push2::stop ()
198 {
199         BaseUI::quit ();
200         close ();
201         return 0;
202 }
203
204 /** render host-side frame buffer (a Cairo ImageSurface) to the current
205  * device-side frame buffer. The device frame buffer will be pushed to the
206  * device on the next call to vblank()
207  */
208
209 int
210 Push2::render ()
211 {
212         /* ensure that all drawing has been done before we fetch pixel data */
213
214         frame_buffer->flush ();
215
216         const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
217         const uint8_t* data = frame_buffer->get_data ();
218
219         /* fill frame buffer (320kB) */
220
221         Glib::Threads::Mutex::Lock lm (fb_lock);
222
223         uint16_t* fb = (uint16_t*) device_frame_buffer[device_buffer];
224
225         for (int row = 0; row < rows; ++row) {
226
227                 const uint8_t* dp = data + row * stride;
228
229                 for (int col = 0; col < cols; ++col) {
230
231                         /* fetch r, g, b (range 0..255). Ignore alpha */
232
233                         const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
234                         const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
235                         const int b = *((const uint32_t*)dp) & 0xff;
236
237                         /* convert to 5 bits, 6 bits, 5 bits, respectively */
238                         /* generate 16 bit BGB565 value */
239
240                         *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
241
242                         dp += 4;
243                 }
244
245                 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
246                    byte USB buffers
247                 */
248
249                 fb += 64; /* 128 bytes = 64 int16_t */
250         }
251
252         /* swap buffers (under lock protection) */
253         // device_buffer = (device_buffer ? 0 : 1);
254
255         return 0;
256 }
257
258 bool
259 Push2::vblank ()
260 {
261         int transferred = 0;
262         const int timeout_msecs = 1000;
263         int err;
264
265         if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
266                 return false;
267         }
268
269         {
270                 Glib::Threads::Mutex::Lock lm (fb_lock);
271
272                 if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer[device_buffer] , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
273                         return false;
274                 }
275         }
276
277         return true;
278 }
279
280 int
281 Push2::set_active (bool yn)
282 {
283         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
284
285         if (yn == active()) {
286                 return 0;
287         }
288
289         if (yn) {
290
291                 /* start event loop */
292
293                 BaseUI::run ();
294
295                 if (open ()) {
296                         DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
297                         close ();
298                         return -1;
299                 }
300
301                 // connect_session_signals ();
302
303                 /* say hello */
304
305                 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (frame_buffer);
306                 if (!context) {
307                         cerr << "Cannot create context\n";
308                         return -1;
309                 }
310                 Glib::RefPtr<Pango::Layout> layout = Pango::Layout::create (context);
311                 if (!layout) {
312                         cerr << "Cannot create layout\n";
313                         return -1;
314                 }
315
316                 layout->set_text ("hello, Ardour");
317                 Pango::FontDescription fd ("Sans Bold 12");
318                 layout->set_font_description (fd);
319
320                 context->set_source_rgb (0.0, 1.0, 1.0);
321                 context->rectangle (0, 0, 960, 160);
322                 context->fill ();
323                 context->set_source_rgb (0.0, 0.0, 0.0);
324                 context->rectangle (50, 50, 860, 60);
325                 context->fill ();
326                 context->move_to (60, 60);
327                 context->set_source_rgb ((random()%255) / 255.0, (random()%255) / 255.0, (random()%255) / 255.0);
328                 layout->update_from_cairo_context (context);
329                 layout->show_in_cairo_context (context);
330
331                 render ();
332
333                 /* set up periodic task used to push a frame buffer to the
334                  * device (25fps). The device can handle 60fps, but we don't
335                  * need that frame rate.
336                  */
337
338                 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
339                 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
340                 vblank_timeout->attach (main_loop()->get_context());
341
342         } else {
343
344                 stop ();
345
346         }
347
348         ControlProtocol::set_active (yn);
349
350         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
351
352         return 0;
353 }
354
355 void
356 Push2::write (int port, const MidiByteArray& data)
357 {
358         /* immediate delivery */
359         _output_port[port]->write (&data[0], data.size(), 0);
360 }
361
362 bool
363 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
364 {
365         if (ioc & ~IO_IN) {
366                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
367                 return false;
368         }
369
370         if (ioc & IO_IN) {
371
372                 DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
373
374                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
375                 if (asp) {
376                         asp->clear ();
377                 }
378
379                 DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
380                 framepos_t now = AudioEngine::instance()->sample_time();
381                 // port->parse (now);
382         }
383
384         return true;
385 }