MCP: build fix
[ardour.git] / libs / surfaces / mackie / mackie_port.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
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 #include "mackie_port.h"
19
20 #include "mackie_control_exception.h"
21 #include "mackie_control_protocol.h"
22 #include "mackie_midi_builder.h"
23 #include "controls.h"
24 #include "surface.h"
25
26 #include <glibmm/main.h>
27
28 #include <boost/shared_array.hpp>
29
30 #include "midi++/types.h"
31 #include "midi++/port.h"
32
33 #include "ardour/debug.h"
34 #include "ardour/rc_configuration.h"
35
36 #include "i18n.h"
37
38 #include <sstream>
39
40 using namespace std;
41 using namespace Mackie;
42 using namespace ARDOUR;
43 using namespace PBD;
44
45 // The MCU sysex header
46 MidiByteArray mackie_sysex_hdr  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x10);
47
48 // The MCU extender sysex header
49 MidiByteArray mackie_sysex_hdr_xt  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x11);
50
51 MackiePort::MackiePort (MackieControlProtocol & mcp, MIDI::Port & input_port, MIDI::Port & output_port, int number, port_type_t port_type)
52         : SurfacePort (input_port, output_port, number)
53         , _mcp (mcp)
54         , _port_type (port_type)
55         , _emulation (none)
56         , _initialising (true)
57 {
58         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::MackiePort\n");
59 }
60
61 MackiePort::~MackiePort()
62 {
63         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::~MackiePort\n");
64         close();
65         DEBUG_TRACE (DEBUG::MackieControl, "~MackiePort finished\n");
66 }
67
68 int MackiePort::strips() const
69 {
70         if  (_port_type == mcu)
71         {
72                 switch  (_emulation)
73                 {
74                         // BCF2000 only has 8 faders, so reserve one for master
75                         case bcf2000: return 7;
76                         case mackie: return 8;
77                         case none:
78                         default:
79                                 throw MackieControlException ("MackiePort::strips: don't know what emulation we're using");
80                 }
81         }
82         else
83         {
84                 // must be an extender, ie no master fader
85                 return 8;
86         }
87 }
88
89 // should really be in MackiePort
90 void MackiePort::open()
91 {
92         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackiePort::open %1\n", *this));
93         
94         input_port().parser()->sysex.connect_same_thread (sysex_connection, boost::bind (&MackiePort::handle_midi_sysex, this, _1, _2, _3));
95                      
96         // make sure the device is connected
97         init();
98 }
99
100 void MackiePort::close()
101 {
102         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::close\n");
103         
104         // disconnect signals
105         any_connection.disconnect();
106         sysex_connection.disconnect();
107         
108         // TODO emit a "closing" signal?
109 }
110
111 const MidiByteArray & MackiePort::sysex_hdr() const
112 {
113         switch  (_port_type)
114         {
115                 case mcu: return mackie_sysex_hdr;
116                 case ext: return mackie_sysex_hdr_xt;
117         }
118         cout << "MackiePort::sysex_hdr _port_type not known" << endl;
119         return mackie_sysex_hdr;
120 }
121
122 MidiByteArray calculate_challenge_response (MidiByteArray::iterator begin, MidiByteArray::iterator end)
123 {
124         MidiByteArray l;
125         back_insert_iterator<MidiByteArray> back  (l);
126         copy (begin, end, back);
127         
128         MidiByteArray retval;
129         
130         // this is how to calculate the response to the challenge.
131         // from the Logic docs.
132         retval <<  (0x7f &  (l[0] +  (l[1] ^ 0xa) - l[3]));
133         retval <<  (0x7f &  ( (l[2] >> l[3]) ^  (l[0] + l[3])));
134         retval <<  (0x7f &  ((l[3] -  (l[2] << 2)) ^  (l[0] | l[1])));
135         retval <<  (0x7f &  (l[1] - l[2] +  (0xf0 ^  (l[3] << 4))));
136         
137         return retval;
138 }
139
140 // not used right now
141 MidiByteArray MackiePort::host_connection_query (MidiByteArray & bytes)
142 {
143         MidiByteArray response;
144
145         // handle host connection query
146         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host connection query: %1\n", bytes));
147         
148         if  (bytes.size() != 18) {
149                 finalise_init (false);
150                 cerr << "expecting 18 bytes, read " << bytes << " from " << input_port().name() << endl;
151                 return response;
152         }
153
154         // build and send host connection reply
155         response << 0x02;
156         copy (bytes.begin() + 6, bytes.begin() + 6 + 7, back_inserter (response));
157         response << calculate_challenge_response (bytes.begin() + 6 + 7, bytes.begin() + 6 + 7 + 4);
158         return response;
159 }
160
161 // not used right now
162 MidiByteArray MackiePort::host_connection_confirmation (const MidiByteArray & bytes)
163 {
164         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host_connection_confirmation: %1\n", bytes));
165         
166         // decode host connection confirmation
167         if  (bytes.size() != 14) {
168                 finalise_init (false);
169                 ostringstream os;
170                 os << "expecting 14 bytes, read " << bytes << " from " << input_port().name();
171                 throw MackieControlException (os.str());
172         }
173         
174         // send version request
175         return MidiByteArray (2, 0x13, 0x00);
176 }
177
178 void MackiePort::probe_emulation (const MidiByteArray &)
179 {
180 #if 0
181         cout << "MackiePort::probe_emulation: " << bytes.size() << ", " << bytes << endl;
182
183         MidiByteArray version_string;
184         for  (int i = 6; i < 11; ++i) version_string << bytes[i];
185         cout << "version_string: " << version_string << endl;
186 #endif
187         
188         // TODO investigate using serial number. Also, possibly size of bytes might
189         // give an indication. Also, apparently MCU sends non-documented messages
190         // sometimes.
191         if (!_initialising)
192         {
193                 //cout << "MackiePort::probe_emulation out of sequence." << endl;
194                 return;
195         }
196
197         finalise_init (true);
198 }
199
200 void MackiePort::init()
201 {
202         DEBUG_TRACE (DEBUG::MackieControl,  "MackiePort::init\n");
203
204         init_mutex.lock();
205         _initialising = true;
206
207         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::init lock acquired\n");
208
209         // emit pre-init signal
210         init_event();
211         
212         // kick off initialisation. See docs in header file for init()
213         
214         // bypass the init sequence because sometimes the first
215         // message doesn't get to the unit, and there's no way
216         // to do a timed lock in Glib.
217         //write_sysex  (MidiByteArray  (2, 0x13, 0x00));
218         
219         finalise_init (true);
220 }
221
222 void MackiePort::finalise_init (bool yn)
223 {
224         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::finalise_init\n");
225
226         bool emulation_ok = false;
227         
228         // probing doesn't work very well, so just use a config variable
229         // to set the emulation mode
230         // TODO This might have to be specified on a per-port basis
231         // in the config file
232         // if an mcu and a bcf are needed to work as one surface
233         if  (_emulation == none)
234         {
235                 // TODO same as code in mackie_control_protocol.cc
236                 if  (ARDOUR::Config->get_mackie_emulation() == "bcf")
237                 {
238                         _emulation = bcf2000;
239                         emulation_ok = true;
240                 }
241                 else if  (ARDOUR::Config->get_mackie_emulation() == "mcu")
242                 {
243                         _emulation = mackie;
244                         emulation_ok = true;
245                 }
246                 else
247                 {
248                         cout << "unknown mackie emulation: " << ARDOUR::Config->get_mackie_emulation() << endl;
249                         emulation_ok = false;
250                 }
251         }
252         
253         yn = yn && emulation_ok;
254         
255         SurfacePort::active (yn);
256
257         if (yn) {
258                 active_event();
259                 
260                 // start handling messages from controls
261                 connect_any();
262         }
263
264         _initialising = false;
265         init_cond.signal();
266         init_mutex.unlock();
267
268         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::finalise_init lock released\n");
269 }
270
271 void MackiePort::connect_any()
272 {
273         if (!any_connection.connected()) {
274                 input_port().parser()->any.connect_same_thread (any_connection, boost::bind (&MackiePort::handle_midi_any, this, _1, _2, _3));
275         }
276 }
277
278 bool MackiePort::wait_for_init()
279 {
280         Glib::Mutex::Lock lock (init_mutex);
281         while (_initialising) {
282                 DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::wait_for_active waiting\n");
283                 init_cond.wait (init_mutex);
284                 DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::wait_for_active released\n");
285         }
286         DEBUG_TRACE (DEBUG::MackieControl, "MackiePort::wait_for_active returning\n");
287         return SurfacePort::active();
288 }
289
290 void MackiePort::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
291 {
292         MidiByteArray bytes (count, raw_bytes);
293
294         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi_sysex: %1\n", bytes));
295
296         switch (bytes[5])
297         {
298                 case 0x01:
299                         write_sysex (host_connection_query (bytes));
300                         break;
301                 case 0x03:
302                         // not used right now
303                         write_sysex (host_connection_confirmation (bytes));
304                         break;
305                 case 0x04:
306                         inactive_event ();
307                         cout << "host connection error" << bytes << endl;
308                         break;
309                 case 0x14:
310                         probe_emulation (bytes);
311                         break;
312                 default:
313                         cout << "unknown sysex: " << bytes << endl;
314         }
315 }
316
317 Control & MackiePort::lookup_control (MIDI::byte * bytes, size_t count)
318 {
319         // Don't instantiate a MidiByteArray here unless it's needed for exceptions.
320         // Reason being that this method is called for every single incoming
321         // midi event, and it needs to be as efficient as possible.
322
323         Control * control = 0;
324         MIDI::byte midi_type = bytes[0] & 0xf0; //0b11110000
325
326         switch (midi_type) {
327                 // fader
328                 case MackieMidiBuilder::midi_fader_id:
329                 {
330                         int midi_id = bytes[0] & 0x0f;
331                         control = _mcp.surface().faders[midi_id];
332                         if  (control == 0)
333                         {
334                                 MidiByteArray mba (count, bytes);
335                                 ostringstream os;
336                                 os << "Control for fader" << bytes << " id " << midi_id << " is null";
337                                 throw MackieControlException (os.str());
338                         }
339                         break;
340                 }
341                         
342                 // button
343                 case MackieMidiBuilder::midi_button_id:
344                         control = _mcp.surface().buttons[bytes[1]];
345                         if  (control == 0)
346                         {
347                                 MidiByteArray mba (count, bytes);
348                                 ostringstream os;
349                                 os << "Control for button " << mba << " is null";
350                                 throw MackieControlException (os.str());
351                         }
352                         break;
353                         
354                 // pot (jog wheel, external control)
355                 case MackieMidiBuilder::midi_pot_id:
356                         control = _mcp.surface().pots[bytes[1]];
357                         if  (control == 0)
358                         {
359                                 MidiByteArray mba (count, bytes);
360                                 ostringstream os;
361                                 os << "Control for rotary " << mba << " is null";
362                                 throw MackieControlException (os.str());
363                         }
364                         break;
365                 
366                 default:
367                         MidiByteArray mba (count, bytes);
368                         ostringstream os;
369                         os << "Cannot find control for " << mba;
370                         throw MackieControlException (os.str());
371         }
372         return *control;
373 }
374
375 // converts midi messages into control_event signals
376 // it might be worth combining this with lookup_control
377 // because they have similar logic flows.
378 void MackiePort::handle_midi_any (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
379 {
380         MidiByteArray bytes (count, raw_bytes);
381         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackiePort::handle_midi_any %1\n", bytes));
382
383         try
384         {
385                 // ignore sysex messages
386                 if  (raw_bytes[0] == MIDI::sysex) return;
387
388                 // sanity checking
389                 if (count != 3) {
390                         ostringstream os;
391                         MidiByteArray mba (count, raw_bytes);
392                         os << "MackiePort::handle_midi_any needs 3 bytes, but received " << mba;
393                         throw MackieControlException (os.str());
394                 }
395                 
396                 Control & control = lookup_control (raw_bytes, count);
397                 control.set_in_use (true);
398                 
399                 // This handles incoming bytes. Outgoing bytes
400                 // are sent by the signal handlers.
401                 switch (control.type()) {
402                         // fader
403                         case Control::type_fader:
404                         {
405                                 // only the top-order 10 bits out of 14 are used
406                                 int midi_pos =  ( (raw_bytes[2] << 7) + raw_bytes[1]) >> 4;
407                                 
408                                 // in_use is set by the MackieControlProtocol::handle_strip_button
409                                 
410                                 // relies on implicit ControlState constructor
411                                 control_event (*this, control, float(midi_pos) / float(0x3ff));
412                         }
413                         break;
414                                 
415                         // button
416                         case Control::type_button:
417                         {
418                                 ControlState control_state (raw_bytes[2] == 0x7f ? press : release);
419                                 control.set_in_use (control_state.button_state == press);
420                                 control_event (*this, control, control_state);
421                                 
422                                 break;
423                         }
424                                 
425                         // pot (jog wheel, external control)
426                         case Control::type_pot:
427                         {
428                                 ControlState state;
429                                 
430                                 // bytes[2] & 0b01000000 (0x40) give sign
431                                 state.sign =  (raw_bytes[2] & 0x40) == 0 ? 1 : -1; 
432                                 // bytes[2] & 0b00111111 (0x3f) gives delta
433                                 state.ticks =  (raw_bytes[2] & 0x3f);
434                                 if (state.ticks == 0) {
435                                         /* euphonix and perhaps other devices send zero
436                                            when they mean 1, we think.
437                                         */
438                                         state.ticks = 1;
439                                 }
440                                 state.delta = float (state.ticks) / float (0x3f);
441                                 
442                                 /* Pots only emit events when they move, not when they
443                                    stop moving. So to get a stop event, we need to use a timeout.
444                                 */
445
446                                 control.set_in_use (true);
447                                 add_in_use_timeout (control, &control);
448
449                                 // emit the control event
450                                 control_event (*this, control, state);
451                                 break;
452                         }
453                         default:
454                                 cerr << "Do not understand control type " << control;
455                 }
456         }
457
458         catch (MackieControlException & e) {
459                 MidiByteArray bytes (count, raw_bytes);
460                 cout << bytes << ' ' << e.what() << endl;
461         }
462
463         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("finished MackiePort::handle_midi_any %1\n", bytes));
464 }
465