a4b1feccad54a90c0f7b9ee9f415918286dd4d04
[ardour.git] / libs / surfaces / mackie / surface.cc
1 /*
2     Copyright (C) 2012 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
20 #include <sstream>
21 #include <iomanip>
22 #include <iostream>
23 #include <cstdio>
24 #include <cmath>
25
26 #include "midi++/port.h"
27
28 #include "ardour/automation_control.h"
29 #include "ardour/debug.h"
30 #include "ardour/route.h"
31 #include "ardour/panner.h"
32 #include "ardour/panner_shell.h"
33 #include "ardour/rc_configuration.h"
34 #include "ardour/session.h"
35 #include "ardour/utils.h"
36
37 #include "control_group.h"
38 #include "surface_port.h"
39 #include "surface.h"
40 #include "strip.h"
41 #include "mackie_control_protocol.h"
42 #include "jog_wheel.h"
43
44 #include "strip.h"
45 #include "button.h"
46 #include "led.h"
47 #include "pot.h"
48 #include "fader.h"
49 #include "jog.h"
50 #include "meter.h"
51
52 #include "i18n.h"
53
54 #ifdef PLATFORM_WINDOWS
55 #define random() rand()
56 #endif
57
58 using namespace std;
59 using namespace PBD;
60 using ARDOUR::Route;
61 using ARDOUR::Panner;
62 using ARDOUR::Pannable;
63 using ARDOUR::AutomationControl;
64 using namespace ArdourSurface;
65 using namespace Mackie;
66
67 #define ui_context() MackieControlProtocol::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
68
69 // The MCU sysex header.4th byte Will be overwritten
70 // when we get an incoming sysex that identifies
71 // the device type
72 static MidiByteArray mackie_sysex_hdr  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x14);
73
74 // The MCU extender sysex header.4th byte Will be overwritten
75 // when we get an incoming sysex that identifies
76 // the device type
77 static MidiByteArray mackie_sysex_hdr_xt  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x15);
78
79 static MidiByteArray empty_midi_byte_array;
80
81 Surface::Surface (MackieControlProtocol& mcp, const std::string& device_name, uint32_t number, surface_type_t stype)
82         : _mcp (mcp)
83         , _stype (stype)
84         , _number (number)
85         , _name (device_name)
86         , _active (false)
87         , _connected (false)
88         , _jog_wheel (0)
89         , _master_fader (0)
90         , _last_master_gain_written (-0.0f)
91 {
92         DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface init\n");
93         
94         try {
95                 _port = new SurfacePort (*this);
96         } catch (...) {
97                 throw failed_constructor ();
98         }
99
100         /* only the first Surface object has global controls */
101         /* lets use master_position instead */
102         uint32_t mp = _mcp.device_info().master_position();
103         if (_number == mp) {
104                 DEBUG_TRACE (DEBUG::MackieControl, "Surface matches MasterPosition. Might have global controls.\n");
105                 if (_mcp.device_info().has_global_controls()) {
106                         init_controls ();
107                         DEBUG_TRACE (DEBUG::MackieControl, "init_controls done\n");
108                 }
109
110                 if (_mcp.device_info().has_master_fader()) {
111                         setup_master ();
112                         DEBUG_TRACE (DEBUG::MackieControl, "setup_master done\n");
113                 }
114         }
115
116         uint32_t n = _mcp.device_info().strip_cnt();
117         
118         if (n) {
119                 init_strips (n);
120                 DEBUG_TRACE (DEBUG::MackieControl, "init_strips done\n");
121         }
122         
123         connect_to_signals ();
124
125         DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface done\n");
126 }
127
128 Surface::~Surface ()
129 {
130         DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface init\n");
131
132         // zero_all ();
133
134         // delete groups
135         for (Groups::iterator it = groups.begin(); it != groups.end(); ++it) {
136                 delete it->second;
137         }
138         
139         // delete controls
140         for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
141                 delete *it;
142         }
143         
144         delete _jog_wheel;
145         delete _port;
146
147         DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface done\n");
148 }
149
150 XMLNode&
151 Surface::get_state()
152 {
153         char buf[64];
154         snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
155         XMLNode* node = new XMLNode (buf);
156
157         node->add_child_nocopy (_port->get_state());
158
159         return *node;
160 }
161
162 int
163 Surface::set_state (const XMLNode& node, int version)
164 {
165         char buf[64];
166         snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
167         XMLNode* mynode = node.child (buf);
168
169         if (!mynode) {
170                 return 0;
171         }
172
173         XMLNode* portnode = mynode->child (X_("Port"));
174         if (portnode) {
175                 if (_port->set_state (*portnode, version)) {
176                         return -1;
177                 }
178         }
179
180         return 0;
181 }
182
183 const MidiByteArray& 
184 Surface::sysex_hdr() const
185 {
186         switch  (_stype) {
187         case mcu: return mackie_sysex_hdr;
188         case ext: return mackie_sysex_hdr_xt;
189         }
190         cout << "SurfacePort::sysex_hdr _port_type not known" << endl;
191         return mackie_sysex_hdr;
192 }
193
194 static GlobalControlDefinition mackie_global_controls[] = {
195         { "external", Pot::External, Pot::factory, "none" },
196         { "fader_touch", Led::FaderTouch, Led::factory, "master" },
197         { "timecode", Led::Timecode, Led::factory, "none" },
198         { "beats", Led::Beats, Led::factory, "none" },
199         { "solo", Led::RudeSolo, Led::factory, "none" },
200         { "relay_click", Led::RelayClick, Led::factory, "none" },
201         { "", 0, Led::factory, "" }
202 };
203
204 void 
205 Surface::init_controls()
206 {
207         Group* group;
208         
209         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating groups\n");
210         groups["assignment"] = new Group  ("assignment");
211         groups["automation"] = new Group  ("automation");
212         groups["bank"] = new Group  ("bank");
213         groups["cursor"] = new Group  ("cursor");
214         groups["display"] = new Group  ("display");
215         groups["function select"] = new Group  ("function select");
216         groups["global view"] = new Group ("global view");
217         groups["master"] = new Group ("master");
218         groups["modifiers"] = new Group  ("modifiers");
219         groups["none"] = new Group  ("none");
220         groups["transport"] = new Group  ("transport");
221         groups["user"] = new Group  ("user");
222         groups["utilities"] = new Group  ("utilities");
223                 
224         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating jog wheel\n");
225         if (_mcp.device_info().has_jog_wheel()) {
226                 _jog_wheel = new Mackie::JogWheel (_mcp);
227         }
228
229         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating global controls\n");
230         for (uint32_t n = 0; mackie_global_controls[n].name[0]; ++n) {
231                 group = groups[mackie_global_controls[n].group_name];
232                 Control* control = mackie_global_controls[n].factory (*this, mackie_global_controls[n].id, mackie_global_controls[n].name, *group);
233                 controls_by_device_independent_id[mackie_global_controls[n].id] = control;
234         }
235
236         /* add global buttons */
237         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: adding global buttons\n");
238         const map<Button::ID,GlobalButtonInfo>& global_buttons (_mcp.device_info().global_buttons());
239
240         for (map<Button::ID,GlobalButtonInfo>::const_iterator b = global_buttons.begin(); b != global_buttons.end(); ++b){
241                 group = groups[b->second.group];
242                 controls_by_device_independent_id[b->first] = Button::factory (*this, b->first, b->second.id, b->second.label, *group);
243         }
244 }
245
246 void 
247 Surface::init_strips (uint32_t n)
248 {
249         const map<Button::ID,StripButtonInfo>& strip_buttons (_mcp.device_info().strip_buttons());
250
251         for (uint32_t i = 0; i < n; ++i) {
252
253                 char name[32];
254                 
255                 snprintf (name, sizeof (name), "strip_%d", (8* _number) + i);
256
257                 Strip* strip = new Strip (*this, name, i, strip_buttons);
258                 
259                 groups[name] = strip;
260                 strips.push_back (strip);
261         }
262 }
263
264 void
265 Surface::setup_master ()
266 {
267         boost::shared_ptr<Route> m;
268         
269         if ((m = _mcp.get_session().monitor_out()) == 0) {
270                 m = _mcp.get_session().master_out();
271         } 
272         
273         if (!m) {
274                 return;
275         }
276
277         _master_fader = dynamic_cast<Fader*> (Fader::factory (*this, _mcp.device_info().strip_cnt(), "master", *groups["master"]));
278         
279         _master_fader->set_control (m->gain_control());
280         m->gain_control()->Changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&Surface::master_gain_changed, this), ui_context());
281
282         Groups::iterator group_it;
283         group_it = groups.find("master");
284
285         DeviceInfo device_info = _mcp.device_info();
286         GlobalButtonInfo master_button = device_info.get_global_button(Button::MasterFaderTouch);
287         Button* bb = dynamic_cast<Button*> (Button::factory (
288                 *this,
289                 Button::MasterFaderTouch,
290                 master_button.id,
291                 master_button.label,
292                 *(group_it->second)
293 ));
294         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 Master Fader new button BID %2 id %3\n",
295                 number(), Button::MasterFaderTouch, bb->id()));
296 }
297
298 void
299 Surface::master_gain_changed ()
300 {
301         if (!_master_fader) {
302                 return;
303         }
304
305         boost::shared_ptr<AutomationControl> ac = _master_fader->control();
306         if (!ac) {
307                 return;
308         }
309
310         float normalized_position = ac->internal_to_interface (ac->get_value());
311         if (normalized_position == _last_master_gain_written) {
312                 return;
313         }
314
315         DEBUG_TRACE (DEBUG::MackieControl, "Surface::master_gain_changed: updating surface master fader\n");
316
317         _port->write (_master_fader->set_position (normalized_position));
318         _last_master_gain_written = normalized_position;
319 }
320
321 float 
322 Surface::scaled_delta (float delta, float current_speed)
323 {
324         /* XXX needs work before use */
325         const float sign = delta < 0.0 ? -1.0 : 1.0;
326
327         return ((sign * std::pow (delta + 1.0, 2.0)) + current_speed) / 100.0;
328 }
329
330 void 
331 Surface::display_bank_start (uint32_t current_bank)
332 {
333         if  (current_bank == 0) {
334                 // send Ar. to 2-char display on the master
335                 show_two_char_display ("Ar", "..");
336         } else {
337                 // write the current first remote_id to the 2-char display
338                 show_two_char_display (current_bank);
339         }
340 }
341
342 void 
343 Surface::blank_jog_ring ()
344 {
345         Control* control = controls_by_device_independent_id[Jog::ID];
346
347         if (control) {
348                 Pot* pot = dynamic_cast<Pot*> (control);
349                 if (pot) {
350                         _port->write (pot->set (0.0, false, Pot::spread));
351                 }
352         }
353 }
354
355 float
356 Surface::scrub_scaling_factor () const
357 {
358         return 100.0;
359 }
360
361 void 
362 Surface::connect_to_signals ()
363 {
364         if (!_connected) {
365
366
367                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 connecting to signals on port %2\n", 
368                                                                    number(), _port->input_port().name()));
369
370                 MIDI::Parser* p = _port->input_port().parser();
371
372                 /* Incoming sysex */
373                 p->sysex.connect_same_thread (*this, boost::bind (&Surface::handle_midi_sysex, this, _1, _2, _3));
374                 /* V-Pot messages are Controller */
375                 p->controller.connect_same_thread (*this, boost::bind (&Surface::handle_midi_controller_message, this, _1, _2));
376                 /* Button messages are NoteOn */
377                 p->note_on.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
378                 /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
379                 p->note_off.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
380                 /* Fader messages are Pitchbend */
381                 uint32_t i;
382                 for (i = 0; i < _mcp.device_info().strip_cnt(); i++) {
383                         p->channel_pitchbend[i].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, i));
384                 }
385                 // Master fader
386                 p->channel_pitchbend[_mcp.device_info().strip_cnt()].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, _mcp.device_info().strip_cnt()));
387                 
388                 _connected = true;
389         }
390 }
391
392 void
393 Surface::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb, uint32_t fader_id)
394 {
395         /* Pitchbend messages are fader position messages. Nothing in the data we get
396          * from the MIDI::Parser conveys the fader ID, which was given by the
397          * channel ID in the status byte.
398          *
399          * Instead, we have used bind() to supply the fader-within-strip ID 
400          * when we connected to the per-channel pitchbend events.
401          */
402
403         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_pitchbend_message on port %3, fader = %1 value = %2 (%4)\n",
404                                                            fader_id, pb, _number, pb/16384.0));
405         
406         if (_mcp.device_info().no_handshake()) {
407                 turn_it_on ();
408         }
409
410         if (_mcp.main_modifier_state() & MackieControlProtocol::MODIFIER_SHIFT) {
411                 /* user is doing a reset to unity gain but device sends a PB
412                  * message in the middle of the touch on/off messages. Ignore
413                  * it.
414                  */
415                 return;
416         }
417
418         Fader* fader = faders[fader_id];
419
420         if (fader) {
421                 Strip* strip = dynamic_cast<Strip*> (&fader->group());
422                 float pos = pb / 16384.0;
423                 if (strip) {
424                         strip->handle_fader (*fader, pos);
425                 } else {
426                         DEBUG_TRACE (DEBUG::MackieControl, "Handling master fader\n");
427                         /* master fader */
428                         fader->set_value (pos); // alter master gain
429                         _port->write (fader->set_position (pos)); // write back value (required for servo)
430                 }
431         } else {
432                 DEBUG_TRACE (DEBUG::MackieControl, "fader not found\n");
433         }
434 }
435
436 void 
437 Surface::handle_midi_note_on_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
438 {
439         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_note_on_message %1 = %2\n", (int) ev->note_number, (int) ev->velocity));
440         
441         if (_mcp.device_info().no_handshake()) {
442                 turn_it_on ();
443         } 
444
445         if (_mcp.device_info().device_type() == DeviceInfo::HUI && ev->note_number == 0 && ev->velocity == 127) {
446                 turn_it_on ();
447         }
448         
449         /* fader touch sense is given by "buttons" 0xe..0xe7 and 0xe8 for the
450          * master. 
451          */
452
453         if (ev->note_number >= 0xE0 && ev->note_number <= 0xE8) {
454                 Fader* fader = faders[ev->note_number];
455
456                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface: fader touch message, fader = %1\n", fader));
457
458                 if (fader) {
459
460                         Strip* strip = dynamic_cast<Strip*> (&fader->group());
461
462                         if (ev->velocity > 64) {
463                                 strip->handle_fader_touch (*fader, true);
464                         } else {
465                                 strip->handle_fader_touch (*fader, false);
466                         }
467                 }
468                 return;
469         }
470
471         Button* button = buttons[ev->note_number];
472
473         if (button) {
474                 Strip* strip = dynamic_cast<Strip*> (&button->group());
475
476                 if (strip) {
477                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("strip %1 button %2 pressed ? %3\n",
478                                                                            strip->index(), button->name(), (ev->velocity > 64)));
479                         strip->handle_button (*button, ev->velocity > 64 ? press : release);
480                 } else {
481                         /* global button */
482                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("global button %1\n", button->id()));
483                         _mcp.handle_button_event (*this, *button, ev->velocity > 64 ? press : release);
484                 }
485         } else {
486                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button found for %1\n", (int) ev->note_number));
487         }
488 }
489
490 void 
491 Surface::handle_midi_controller_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
492 {
493         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("SurfacePort::handle_midi_controller %1 = %2\n", (int) ev->controller_number, (int) ev->value));
494
495         if (_mcp.device_info().no_handshake()) {
496                 turn_it_on ();
497         }
498
499         Pot* pot = pots[ev->controller_number];
500
501         // bit 6 gives the sign
502         float sign = (ev->value & 0x40) == 0 ? 1.0 : -1.0; 
503         // bits 0..5 give the velocity. we interpret this as "ticks
504         // moved before this message was sent"
505         float ticks = (ev->value & 0x3f);
506         if (ticks == 0) {
507                 /* euphonix and perhaps other devices send zero
508                    when they mean 1, we think.
509                 */
510                 ticks = 1;
511         }
512
513         float delta = 0;
514         if (mcp().main_modifier_state() == MackieControlProtocol::MODIFIER_CONTROL) {
515                 delta = sign * (ticks / (float) 0xff);
516         } else {
517                 delta = sign * (ticks / (float) 0x3f);
518         }
519         
520         if (!pot) {
521                 if (ev->controller_number == Jog::ID && _jog_wheel) {
522
523                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Jog wheel moved %1\n", ticks));
524                         _jog_wheel->jog_event (delta);
525                         return;
526                 }
527                 // add external (pedal?) control here
528
529                 return;
530         }
531
532         Strip* strip = dynamic_cast<Strip*> (&pot->group());
533         if (strip) {
534                 strip->handle_pot (*pot, delta);
535         } 
536 }
537
538 void 
539 Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
540 {
541         MidiByteArray bytes (count, raw_bytes);
542
543         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi_sysex: %1\n", bytes));
544
545         if (_mcp.device_info().no_handshake()) {
546                 turn_it_on ();
547         }
548
549         /* always save the device type ID so that our outgoing sysex messages
550          * are correct 
551          */
552
553         if (_stype == mcu) {
554                 mackie_sysex_hdr[4] = bytes[4];
555         } else {
556                 mackie_sysex_hdr_xt[4] = bytes[4];
557         }
558
559         switch (bytes[5]) {
560         case 0x01:
561                 /* MCP: Device Ready 
562                    LCP: Connection Challenge 
563                 */
564                 if (bytes[4] == 0x10 || bytes[4] == 0x11) {
565                         DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device connection challenge\n");
566                         write_sysex (host_connection_query (bytes));
567                 } else {
568                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mackie Control Device ready, current status = %1\n", _active));
569                         if (!_active) {
570                                 turn_it_on ();
571                         }
572                 }
573                 break;
574
575         case 0x03: /* LCP Connection Confirmation */
576                 DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device confirms connection, ardour replies\n");
577                 if (bytes[4] == 0x10 || bytes[4] == 0x11) {
578                         write_sysex (host_connection_confirmation (bytes));
579                         _active = true;
580                 }
581                 break;
582
583         case 0x04: /* LCP: Confirmation Denied */
584                 DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device denies connection\n");
585                 _active = false;
586                 break;
587         default:
588                 error << "MCP: unknown sysex: " << bytes << endmsg;
589         }
590 }
591
592 static MidiByteArray 
593 calculate_challenge_response (MidiByteArray::iterator begin, MidiByteArray::iterator end)
594 {
595         MidiByteArray l;
596         back_insert_iterator<MidiByteArray> back  (l);
597         copy (begin, end, back);
598         
599         MidiByteArray retval;
600         
601         // this is how to calculate the response to the challenge.
602         // from the Logic docs.
603         retval <<  (0x7f &  (l[0] +  (l[1] ^ 0xa) - l[3]));
604         retval <<  (0x7f &  ( (l[2] >> l[3]) ^  (l[0] + l[3])));
605         retval <<  (0x7f &  ((l[3] -  (l[2] << 2)) ^  (l[0] | l[1])));
606         retval <<  (0x7f &  (l[1] - l[2] +  (0xf0 ^  (l[3] << 4))));
607         
608         return retval;
609 }
610
611 // not used right now
612 MidiByteArray 
613 Surface::host_connection_query (MidiByteArray & bytes)
614 {
615         MidiByteArray response;
616         
617         if (bytes[4] != 0x10 && bytes[4] != 0x11) {
618                 /* not a Logic Control device - no response required */
619                 return response;
620         }
621
622         // handle host connection query
623         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host connection query: %1\n", bytes));
624         
625         if  (bytes.size() != 18) {
626                 cerr << "expecting 18 bytes, read " << bytes << " from " << _port->input_port().name() << endl;
627                 return response;
628         }
629
630         // build and send host connection reply
631         response << 0x02;
632         copy (bytes.begin() + 6, bytes.begin() + 6 + 7, back_inserter (response));
633         response << calculate_challenge_response (bytes.begin() + 6 + 7, bytes.begin() + 6 + 7 + 4);
634         return response;
635 }
636
637 // not used right now
638 MidiByteArray 
639 Surface::host_connection_confirmation (const MidiByteArray & bytes)
640 {
641         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host_connection_confirmation: %1\n", bytes));
642         
643         // decode host connection confirmation
644         if  (bytes.size() != 14) {
645                 ostringstream os;
646                 os << "expecting 14 bytes, read " << bytes << " from " << _port->input_port().name();
647                 throw MackieControlException (os.str());
648         }
649         
650         // send version request
651         return MidiByteArray (2, 0x13, 0x00);
652 }
653
654 void
655 Surface::turn_it_on ()
656 {
657         if (_active) {
658                 return;
659         }
660
661         _active = true;
662
663         _mcp.device_ready ();
664
665         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
666                 (*s)->notify_all ();
667         }
668
669         update_view_mode_display ();
670
671         if (_mcp.device_info ().has_global_controls ()) {
672                 _mcp.update_global_button (Button::Read, _mcp.metering_active ());
673         }
674 }
675
676 void 
677 Surface::write_sysex (const MidiByteArray & mba)
678 {
679         if (mba.empty()) {
680                 return;
681         }
682
683         MidiByteArray buf;
684         buf << sysex_hdr() << mba << MIDI::eox;
685         _port->write (buf);
686 }
687
688 void 
689 Surface::write_sysex (MIDI::byte msg)
690 {
691         MidiByteArray buf;
692         buf << sysex_hdr() << msg << MIDI::eox;
693         _port->write (buf);
694 }
695
696 uint32_t
697 Surface::n_strips (bool with_locked_strips) const
698 {
699         if (with_locked_strips) {
700                 return strips.size();
701         } 
702
703         uint32_t n = 0;
704
705         for (Strips::const_iterator it = strips.begin(); it != strips.end(); ++it) {
706                 if (!(*it)->locked()) {
707                         ++n;
708                 }
709         }
710         return n;
711 }
712
713 Strip*
714 Surface::nth_strip (uint32_t n) const
715 {
716         if (n > n_strips()) {
717                 return 0;
718         }
719         return strips[n];
720 }
721
722 void
723 Surface::zero_all ()
724 {
725         if (_mcp.device_info().has_timecode_display ()) {
726                 display_timecode (string (10, '0'), string (10, ' '));
727         }
728         
729         if (_mcp.device_info().has_two_character_display()) {
730                 show_two_char_display (string (2, '0'), string (2, ' '));
731         }
732
733         if (_mcp.device_info().has_master_fader () && _master_fader) {
734                 _port->write (_master_fader->zero ());
735         }
736
737         // zero all strips
738         for (Strips::iterator it = strips.begin(); it != strips.end(); ++it) {
739                 (*it)->zero();
740         }
741
742         zero_controls ();
743 }
744
745 void
746 Surface::zero_controls ()
747 {
748         if (!_mcp.device_info().has_global_controls()) {
749                 return;
750         }
751
752         // turn off global buttons and leds
753
754         for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
755                 Control & control = **it;
756                 if (!control.group().is_strip()) {
757                         _port->write (control.zero());
758                 }
759         }
760
761         // and the led ring for the master strip
762         blank_jog_ring ();
763
764         _last_master_gain_written = 0.0f;
765 }
766
767 void
768 Surface::periodic (uint64_t now_usecs)
769 {
770         master_gain_changed();
771         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
772                 (*s)->periodic (now_usecs);
773         }
774 }
775
776 void
777 Surface::redisplay ()
778 {
779         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
780                 (*s)->redisplay ();
781         }
782 }
783
784 void
785 Surface::write (const MidiByteArray& data) 
786 {
787         if (_active) {
788                 _port->write (data);
789         } else {
790                 DEBUG_TRACE (DEBUG::MackieControl, "surface not active, write ignored\n");
791         }
792 }
793
794 void
795 Surface::map_routes (const vector<boost::shared_ptr<Route> >& routes)
796 {
797         vector<boost::shared_ptr<Route> >::const_iterator r;
798         Strips::iterator s = strips.begin();
799
800         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mapping %1 routes\n", routes.size()));
801
802         for (r = routes.begin(); r != routes.end() && s != strips.end(); ++s) {
803
804                 /* don't try to assign routes to a locked strip. it won't
805                    use it anyway, but if we do, then we get out of sync
806                    with the proposed mapping.
807                 */
808
809                 if (!(*s)->locked()) {
810                         (*s)->set_route (*r);
811                         ++r;
812                 }
813         }
814
815         for (; s != strips.end(); ++s) {
816                 (*s)->set_route (boost::shared_ptr<Route>());
817         }
818
819
820 }
821
822 static char 
823 translate_seven_segment (char achar)
824 {
825         achar = toupper (achar);
826
827         if  (achar >= 0x40 && achar <= 0x60) {
828                 return achar - 0x40;
829         } else if  (achar >= 0x21 && achar <= 0x3f) {
830                 return achar;
831         } else {
832                 return 0x00;
833         }
834 }
835
836 void
837 Surface::show_two_char_display (const std::string & msg, const std::string & dots)
838 {
839         if (_stype != mcu || !_mcp.device_info().has_two_character_display() || msg.length() != 2 || dots.length() != 2) {
840                 return;
841         }
842         
843         MidiByteArray right (3, 0xb0, 0x4b, 0x00);
844         MidiByteArray left (3, 0xb0, 0x4a, 0x00);
845         
846         right[2] = translate_seven_segment (msg[0]) +  (dots[0] == '.' ? 0x40 : 0x00);
847         left[2] = translate_seven_segment (msg[1]) +  (dots[1] == '.' ? 0x40 : 0x00);
848         
849         _port->write (right);
850         _port->write (left);
851 }
852
853 void
854 Surface::show_two_char_display (unsigned int value, const std::string & /*dots*/)
855 {
856         ostringstream os;
857         os << setfill('0') << setw(2) << value % 100;
858         show_two_char_display (os.str());
859 }
860
861 void
862 Surface::display_timecode (const std::string & timecode, const std::string & last_timecode)
863 {
864         if (!_active || !_mcp.device_info().has_timecode_display()) {
865                 return;
866         }
867         // if there's no change, send nothing, not even sysex header
868         if  (timecode == last_timecode) return;
869         
870         // length sanity checking
871         string local_timecode = timecode;
872
873         // truncate to 10 characters
874         if  (local_timecode.length() > 10) {
875                 local_timecode = local_timecode.substr (0, 10);
876         }
877
878         // pad to 10 characters
879         while  (local_timecode.length() < 10) { 
880                 local_timecode += " ";
881         }
882         
883         // translate characters.
884         // Only the characters that actually changed are sent.
885         int position = 0x3f;
886         int i;
887         for (i = local_timecode.length () - 1; i >= 0; i--) {
888                 position++;
889                 if (local_timecode[i] == last_timecode[i]) {
890                         continue;
891                 }
892                 MidiByteArray retval (2, 0xb0, position);
893                 retval << translate_seven_segment (local_timecode[i]);
894                 _port->write (retval);
895         }
896 }
897
898 void
899 Surface::update_flip_mode_display ()
900 {
901         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
902                 (*s)->flip_mode_changed (true);
903         }
904 }
905
906 void
907 Surface::update_view_mode_display ()
908 {
909         string text;
910         int id = -1;
911
912         if (!_active) {
913                 return;
914         }
915
916         switch (_mcp.view_mode()) {
917         case MackieControlProtocol::Mixer:
918                 show_two_char_display ("Mx");
919                 id = Button::Pan;
920                 break;
921         case MackieControlProtocol::Dynamics:
922                 show_two_char_display ("Dy");
923                 id = Button::Dyn;
924                 break;
925         case MackieControlProtocol::EQ:
926                 show_two_char_display ("EQ");
927                 id = Button::Eq;
928                 break;
929         case MackieControlProtocol::Loop:
930                 show_two_char_display ("LP");
931                 id = Button::Loop;
932                 break;
933         case MackieControlProtocol::AudioTracks:
934                 show_two_char_display ("AT");
935                 break;
936         case MackieControlProtocol::MidiTracks:
937                 show_two_char_display ("MT");
938                 break;
939         case MackieControlProtocol::Sends:
940                 show_two_char_display ("Sn");
941                 id = Button::Send;
942                 break;
943         case MackieControlProtocol::Plugins:
944                 show_two_char_display ("Pl");
945                 id = Button::Plugin;
946                 break;
947         default:
948                 break;
949         }
950
951         if (id >= 0) {
952                 
953                 /* we are attempting to turn a global button/LED on */
954
955                 map<int,Control*>::iterator x = controls_by_device_independent_id.find (id);
956
957                 if (x != controls_by_device_independent_id.end()) {
958                         Button* button = dynamic_cast<Button*> (x->second);
959                         if (button) {
960                                 _port->write (button->set_state (on));
961                         }
962                 }
963         }
964
965         if (!text.empty()) {
966                 for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
967                         _port->write ((*s)->display (1, text));
968                 }
969         }
970 }
971
972 void
973 Surface::gui_selection_changed (const ARDOUR::StrongRouteNotificationList& routes)
974 {
975         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
976                 (*s)->gui_selection_changed (routes);
977         }
978 }
979
980 void
981 Surface::say_hello ()
982 {
983         /* wakeup for Mackie Control */
984         MidiByteArray wakeup (7, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x00, MIDI::eox);
985         _port->write (wakeup);
986         wakeup[4] = 0x15; /* wakup Mackie XT */
987         _port->write (wakeup);
988         wakeup[4] = 0x10; /* wakeup Logic Control */
989         _port->write (wakeup);
990         wakeup[4] = 0x11; /* wakeup Logic Control XT */
991         _port->write (wakeup);
992 }
993
994 void
995 Surface::next_jog_mode ()
996 {
997 }
998
999 void
1000 Surface::set_jog_mode (JogWheel::Mode)
1001 {
1002 }       
1003
1004 bool
1005 Surface::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
1006 {
1007         for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
1008                 if ((*s)->route() == r && (*s)->locked()) {
1009                         return true;
1010                 }
1011         }
1012         return false;
1013 }
1014
1015 void 
1016 Surface::notify_metering_state_changed()
1017 {
1018         for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
1019                 (*s)->notify_metering_state_changed ();
1020         }
1021 }
1022
1023 void
1024 Surface::reset ()
1025 {
1026         if (_port) {
1027                 /* reset msg for Mackie Control */
1028                 MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x08, 0x00, MIDI::eox);
1029                 _port->write (msg); 
1030                 msg[4] = 0x15; /* reset Mackie XT */
1031                 _port->write (msg);
1032                 msg[4] = 0x10; /* reset Logic Control */
1033                 _port->write (msg);
1034                 msg[4] = 0x11; /* reset Logic Control XT */
1035                 _port->write (msg);
1036         }
1037 }
1038
1039 void
1040 Surface::toggle_backlight ()
1041 {
1042         if (_port) {
1043                 int onoff = random() %2;
1044                 MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x0a, onoff, MIDI::eox);
1045                 _port->write (msg); 
1046                 msg[4] = 0x15; /* reset Mackie XT */
1047                 _port->write (msg);
1048                 msg[4] = 0x10; /* reset Logic Control */
1049                 _port->write (msg);
1050                 msg[4] = 0x11; /* reset Logic Control XT */
1051                 _port->write (msg);
1052         }
1053 }
1054
1055 void
1056 Surface::recalibrate_faders ()
1057 {
1058         if (_port) {
1059                 MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x09, 0x00, MIDI::eox);
1060                 _port->write (msg); 
1061                 msg[4] = 0x15; /* reset Mackie XT */
1062                 _port->write (msg);
1063                 msg[4] = 0x10; /* reset Logic Control */
1064                 _port->write (msg);
1065                 msg[4] = 0x11; /* reset Logic Control XT */
1066                 _port->write (msg);
1067         }
1068 }       
1069
1070 void
1071 Surface::set_touch_sensitivity (int sensitivity)
1072 {
1073         /* NOTE: assumed called from GUI code, hence sleep() */
1074         
1075         /* sensitivity already clamped by caller */
1076
1077         if (_port) {
1078                 MidiByteArray msg (9, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x0e, 0xff, sensitivity, MIDI::eox);
1079
1080                 for (int fader = 0; fader < 9; ++fader) {
1081                         msg[6] = fader;
1082
1083                         _port->write (msg); 
1084                         msg[4] = 0x15; /* reset Mackie XT */
1085                         _port->write (msg);
1086                         msg[4] = 0x10; /* reset Logic Control */
1087                         _port->write (msg);
1088                         msg[4] = 0x11; /* reset Logic Control XT */
1089
1090                         g_usleep (1000); /* milliseconds */
1091                 }
1092         }
1093 }
1094
1095 void
1096 Surface::hui_heartbeat ()
1097 {
1098         if (!_port) {
1099                 return;
1100         }
1101
1102         MidiByteArray msg (3, MIDI::on, 0x0, 0x0);
1103         _port->write (msg);
1104 }