summaryrefslogtreecommitdiff
path: root/libs/surfaces/mackie/surface.cc
blob: b448a7ca19e6abaac742ba130a0ef3ab5c6dbcfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
/*
    Copyright (C) 2012 Paul Davis 

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <sstream>
#include <iomanip>
#include <iostream>
#include <cstdio>
#include <cmath>

#include "midi++/port.h"

#include "ardour/automation_control.h"
#include "ardour/debug.h"
#include "ardour/route.h"
#include "ardour/panner.h"
#include "ardour/panner_shell.h"
#include "ardour/rc_configuration.h"
#include "ardour/session.h"
#include "ardour/utils.h"

#include "control_group.h"
#include "surface_port.h"
#include "surface.h"
#include "strip.h"
#include "mackie_control_protocol.h"
#include "jog_wheel.h"

#include "strip.h"
#include "button.h"
#include "led.h"
#include "pot.h"
#include "fader.h"
#include "jog.h"
#include "meter.h"

#include "i18n.h"

using namespace std;
using namespace PBD;
using ARDOUR::Route;
using ARDOUR::Panner;
using ARDOUR::Pannable;
using ARDOUR::AutomationControl;
using namespace ArdourSurface;
using namespace Mackie;

#define ui_context() MackieControlProtocol::instance() /* a UICallback-derived object that specifies the event loop for signal handling */

// The MCU sysex header.4th byte Will be overwritten
// when we get an incoming sysex that identifies
// the device type
static MidiByteArray mackie_sysex_hdr  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x14);

// The MCU extender sysex header.4th byte Will be overwritten
// when we get an incoming sysex that identifies
// the device type
static MidiByteArray mackie_sysex_hdr_xt  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x15);

static MidiByteArray empty_midi_byte_array;

Surface::Surface (MackieControlProtocol& mcp, const std::string& device_name, uint32_t number, surface_type_t stype)
	: _mcp (mcp)
	, _stype (stype)
	, _number (number)
	, _name (device_name)
	, _active (false)
	, _connected (false)
	, _jog_wheel (0)
	, _master_fader (0)
	, _last_master_gain_written (-0.0f)
{
	DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface init\n");
	
	try {
		_port = new SurfacePort (*this);
	} catch (...) {
		throw failed_constructor ();
	}

	/* only the first Surface object has global controls */
	/* lets use master_position instead */
	uint32_t mp = _mcp.device_info().master_position();
	if (_number == mp) {
		DEBUG_TRACE (DEBUG::MackieControl, "Surface matches MasterPosition. Might have global controls.\n");
		if (_mcp.device_info().has_global_controls()) {
			init_controls ();
			DEBUG_TRACE (DEBUG::MackieControl, "init_controls done\n");
		}

		if (_mcp.device_info().has_master_fader()) {
			setup_master ();
			DEBUG_TRACE (DEBUG::MackieControl, "setup_master done\n");
		}
	}

	uint32_t n = _mcp.device_info().strip_cnt();
	
	if (n) {
		init_strips (n);
		DEBUG_TRACE (DEBUG::MackieControl, "init_strips done\n");
	}
	
	connect_to_signals ();

	DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface done\n");
}

Surface::~Surface ()
{
	DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface init\n");

	zero_all ();

	// delete groups
	for (Groups::iterator it = groups.begin(); it != groups.end(); ++it) {
		delete it->second;
	}
	
	// delete controls
	for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
		delete *it;
	}
	
	delete _jog_wheel;
	delete _port;

	DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface done\n");
}

XMLNode&
Surface::get_state()
{
	char buf[64];
	snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
	XMLNode* node = new XMLNode (buf);

	node->add_child_nocopy (_port->get_state());

	return *node;
}

int
Surface::set_state (const XMLNode& node, int version)
{
	char buf[64];
	snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
	XMLNode* mynode = node.child (buf);

	if (!mynode) {
		return 0;
	}

	XMLNode* portnode = mynode->child (X_("Port"));
	if (portnode) {
		if (_port->set_state (*portnode, version)) {
			return -1;
		}
	}

	return 0;
}

const MidiByteArray& 
Surface::sysex_hdr() const
{
	switch  (_stype) {
	case mcu: return mackie_sysex_hdr;
	case ext: return mackie_sysex_hdr_xt;
	}
	cout << "SurfacePort::sysex_hdr _port_type not known" << endl;
	return mackie_sysex_hdr;
}

static GlobalControlDefinition mackie_global_controls[] = {
	{ "external", Pot::External, Pot::factory, "none" },
	{ "fader_touch", Led::FaderTouch, Led::factory, "master" },
	{ "timecode", Led::Timecode, Led::factory, "none" },
	{ "beats", Led::Beats, Led::factory, "none" },
	{ "solo", Led::RudeSolo, Led::factory, "none" },
	{ "relay_click", Led::RelayClick, Led::factory, "none" },
	{ "", 0, Led::factory, "" }
};

void 
Surface::init_controls()
{
	Group* group;
	
	DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating groups\n");
	groups["assignment"] = new Group  ("assignment");
	groups["automation"] = new Group  ("automation");
	groups["bank"] = new Group  ("bank");
	groups["cursor"] = new Group  ("cursor");
	groups["display"] = new Group  ("display");
	groups["function select"] = new Group  ("function select");
	groups["global view"] = new Group ("global view");
	groups["master"] = new Group ("master");
	groups["modifiers"] = new Group  ("modifiers");
	groups["none"] = new Group  ("none");
	groups["transport"] = new Group  ("transport");
	groups["user"] = new Group  ("user");
	groups["utilities"] = new Group  ("utilities");
		
	DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating jog wheel\n");
	if (_mcp.device_info().has_jog_wheel()) {
		_jog_wheel = new Mackie::JogWheel (_mcp);
	}

	DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating global controls\n");
	for (uint32_t n = 0; mackie_global_controls[n].name[0]; ++n) {
		group = groups[mackie_global_controls[n].group_name];
		Control* control = mackie_global_controls[n].factory (*this, mackie_global_controls[n].id, mackie_global_controls[n].name, *group);
		controls_by_device_independent_id[mackie_global_controls[n].id] = control;
	}

	/* add global buttons */
	DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: adding global buttons\n");
	const map<Button::ID,GlobalButtonInfo>& global_buttons (_mcp.device_info().global_buttons());

	for (map<Button::ID,GlobalButtonInfo>::const_iterator b = global_buttons.begin(); b != global_buttons.end(); ++b){
		group = groups[b->second.group];
		controls_by_device_independent_id[b->first] = Button::factory (*this, b->first, b->second.id, b->second.label, *group);
	}
}

void 
Surface::init_strips (uint32_t n)
{
	const map<Button::ID,StripButtonInfo>& strip_buttons (_mcp.device_info().strip_buttons());

	for (uint32_t i = 0; i < n; ++i) {

		char name[32];
		
		snprintf (name, sizeof (name), "strip_%d", (8* _number) + i);

		Strip* strip = new Strip (*this, name, i, strip_buttons);
		
		groups[name] = strip;
		strips.push_back (strip);
	}
}

void
Surface::setup_master ()
{
	boost::shared_ptr<Route> m;
	
	if ((m = _mcp.get_session().monitor_out()) == 0) {
		m = _mcp.get_session().master_out();
	} 
	
	if (!m) {
		return;
	}

	_master_fader = dynamic_cast<Fader*> (Fader::factory (*this, _mcp.device_info().strip_cnt(), "master", *groups["master"]));
	
	_master_fader->set_control (m->gain_control());
	m->gain_control()->Changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&Surface::master_gain_changed, this), ui_context());

	Groups::iterator group_it;
	group_it = groups.find("master");

	DeviceInfo device_info = _mcp.device_info();
	GlobalButtonInfo master_button = device_info.get_global_button(Button::MasterFaderTouch);
	Button* bb = dynamic_cast<Button*> (Button::factory (
		*this,
		Button::MasterFaderTouch,
		master_button.id,
		master_button.label,
		*(group_it->second)
));
	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 Master Fader new button BID %2 id %3\n",
		number(), Button::MasterFaderTouch, bb->id()));
}

void
Surface::master_gain_changed ()
{
	if (!_master_fader) {
		return;
	}

	boost::shared_ptr<AutomationControl> ac = _master_fader->control();
	if (!ac) {
		return;
	}

	float normalized_position = ac->internal_to_interface (ac->get_value());
	if (normalized_position == _last_master_gain_written) {
		return;
	}

	DEBUG_TRACE (DEBUG::MackieControl, "Surface::master_gain_changed: updating surface master fader\n");

	_port->write (_master_fader->set_position (normalized_position));
	_last_master_gain_written = normalized_position;
}

float 
Surface::scaled_delta (float delta, float current_speed)
{
	/* XXX needs work before use */
	const float sign = delta < 0.0 ? -1.0 : 1.0;

	return ((sign * std::pow (delta + 1.0, 2.0)) + current_speed) / 100.0;
}

void 
Surface::display_bank_start (uint32_t current_bank)
{
	if  (current_bank == 0) {
		// send Ar. to 2-char display on the master
		show_two_char_display ("Ar", "..");
	} else {
		// write the current first remote_id to the 2-char display
		show_two_char_display (current_bank);
	}
}

void 
Surface::blank_jog_ring ()
{
	Control* control = controls_by_device_independent_id[Jog::ID];

	if (control) {
		Pot* pot = dynamic_cast<Pot*> (control);
		if (pot) {
			_port->write (pot->set (0.0, false, Pot::spread));
		}
	}
}

float
Surface::scrub_scaling_factor () const
{
	return 100.0;
}

void 
Surface::connect_to_signals ()
{
	if (!_connected) {


		DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 connecting to signals on port %2\n", 
								   number(), _port->input_port().name()));

		MIDI::Parser* p = _port->input_port().parser();

		/* Incoming sysex */
		p->sysex.connect_same_thread (*this, boost::bind (&Surface::handle_midi_sysex, this, _1, _2, _3));
		/* V-Pot messages are Controller */
		p->controller.connect_same_thread (*this, boost::bind (&Surface::handle_midi_controller_message, this, _1, _2));
		/* Button messages are NoteOn */
		p->note_on.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
		/* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
		p->note_off.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
		/* Fader messages are Pitchbend */
		uint32_t i;
		for (i = 0; i < _mcp.device_info().strip_cnt(); i++) {
			p->channel_pitchbend[i].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, i));
		}
		// Master fader
		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()));
		
		_connected = true;
	}
}

void
Surface::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb, uint32_t fader_id)
{
	/* Pitchbend messages are fader position messages. Nothing in the data we get
	 * from the MIDI::Parser conveys the fader ID, which was given by the
	 * channel ID in the status byte.
	 *
	 * Instead, we have used bind() to supply the fader-within-strip ID 
	 * when we connected to the per-channel pitchbend events.
	 */

	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_pitchbend_message on port %3, fader = %1 value = %2 (%4)\n",
	                                                   fader_id, pb, _number, pb/16384.0));
	
	if (_mcp.device_info().no_handshake()) {
		turn_it_on ();
	}

	Fader* fader = faders[fader_id];

	if (fader) {
		Strip* strip = dynamic_cast<Strip*> (&fader->group());
		float pos = pb / 16384.0;
		if (strip) {
			strip->handle_fader (*fader, pos);
		} else {
			DEBUG_TRACE (DEBUG::MackieControl, "Handling master fader\n");
			/* master fader */
			fader->set_value (pos); // alter master gain
			_port->write (fader->set_position (pos)); // write back value (required for servo)
		}
	} else {
		DEBUG_TRACE (DEBUG::MackieControl, "fader not found\n");
	}
}

void 
Surface::handle_midi_note_on_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
{
	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_note_on_message %1 = %2\n", (int) ev->note_number, (int) ev->velocity));
	
	if (_mcp.device_info().no_handshake()) {
		turn_it_on ();
	}

	/* fader touch sense is given by "buttons" 0xe..0xe7 and 0xe8 for the
	 * master. 
	 */

	if (ev->note_number >= 0xE0 && ev->note_number <= 0xE8) {
		Fader* fader = faders[ev->note_number];

		DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface: fader touch message, fader = %1\n", fader));

		if (fader) {

			Strip* strip = dynamic_cast<Strip*> (&fader->group());

			if (ev->velocity > 64) {
				strip->handle_fader_touch (*fader, true);
			} else {
				strip->handle_fader_touch (*fader, false);
			}
		}
		return;
	}

	Button* button = buttons[ev->note_number];

	if (button) {
		Strip* strip = dynamic_cast<Strip*> (&button->group());

		if (strip) {
			DEBUG_TRACE (DEBUG::MackieControl, string_compose ("strip %1 button %2 pressed ? %3\n",
									   strip->index(), button->name(), (ev->velocity > 64)));
			strip->handle_button (*button, ev->velocity > 64 ? press : release);
		} else {
			/* global button */
			DEBUG_TRACE (DEBUG::MackieControl, string_compose ("global button %1\n", button->id()));
			_mcp.handle_button_event (*this, *button, ev->velocity > 64 ? press : release);
		}
	} else {
		DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button found for %1\n", (int) ev->note_number));
	}
}

void 
Surface::handle_midi_controller_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
{
	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("SurfacePort::handle_midi_controller %1 = %2\n", (int) ev->controller_number, (int) ev->value));

	if (_mcp.device_info().no_handshake()) {
		turn_it_on ();
	}

	Pot* pot = pots[ev->controller_number];

	// bit 6 gives the sign
	float sign = (ev->value & 0x40) == 0 ? 1.0 : -1.0; 
	// bits 0..5 give the velocity. we interpret this as "ticks
	// moved before this message was sent"
	float ticks = (ev->value & 0x3f);
	if (ticks == 0) {
		/* euphonix and perhaps other devices send zero
		   when they mean 1, we think.
		*/
		ticks = 1;
	}

	float delta = 0;
	if (mcp().modifier_state() == MackieControlProtocol::MODIFIER_CONTROL) {
		delta = sign * (ticks / (float) 0xff);
	} else {
		delta = sign * (ticks / (float) 0x3f);
	}
	
	if (!pot) {
		if (ev->controller_number == Jog::ID && _jog_wheel) {

			DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Jog wheel moved %1\n", ticks));
			_jog_wheel->jog_event (delta);
			return;
		}
		// add external (pedal?) control here

		return;
	}

	Strip* strip = dynamic_cast<Strip*> (&pot->group());
	if (strip) {
		strip->handle_pot (*pot, delta);
	} 
}

void 
Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
{
	MidiByteArray bytes (count, raw_bytes);

	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi_sysex: %1\n", bytes));

	if (_mcp.device_info().no_handshake()) {
		turn_it_on ();
	}

	/* always save the device type ID so that our outgoing sysex messages
	 * are correct 
	 */

	if (_stype == mcu) {
		mackie_sysex_hdr[4] = bytes[4];
	} else {
		mackie_sysex_hdr_xt[4] = bytes[4];
	}

	switch (bytes[5]) {
	case 0x01:
		/* MCP: Device Ready 
		   LCP: Connection Challenge 
		*/
		if (bytes[4] == 0x10 || bytes[4] == 0x11) {
			DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device connection challenge\n");
			write_sysex (host_connection_query (bytes));
		} else {
			DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mackie Control Device ready, current status = %1\n", _active));
			if (!_active) {
				turn_it_on ();
			}
		}
		break;

	case 0x03: /* LCP Connection Confirmation */
		DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device confirms connection, ardour replies\n");
		if (bytes[4] == 0x10 || bytes[4] == 0x11) {
			write_sysex (host_connection_confirmation (bytes));
			_active = true;
		}
		break;

	case 0x04: /* LCP: Confirmation Denied */
		DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device denies connection\n");
		_active = false;
		break;
	default:
		error << "MCP: unknown sysex: " << bytes << endmsg;
	}
}

static MidiByteArray 
calculate_challenge_response (MidiByteArray::iterator begin, MidiByteArray::iterator end)
{
	MidiByteArray l;
	back_insert_iterator<MidiByteArray> back  (l);
	copy (begin, end, back);
	
	MidiByteArray retval;
	
	// this is how to calculate the response to the challenge.
	// from the Logic docs.
	retval <<  (0x7f &  (l[0] +  (l[1] ^ 0xa) - l[3]));
	retval <<  (0x7f &  ( (l[2] >> l[3]) ^  (l[0] + l[3])));
	retval <<  (0x7f &  ((l[3] -  (l[2] << 2)) ^  (l[0] | l[1])));
	retval <<  (0x7f &  (l[1] - l[2] +  (0xf0 ^  (l[3] << 4))));
	
	return retval;
}

// not used right now
MidiByteArray 
Surface::host_connection_query (MidiByteArray & bytes)
{
	MidiByteArray response;
	
	if (bytes[4] != 0x10 && bytes[4] != 0x11) {
		/* not a Logic Control device - no response required */
		return response;
	}

	// handle host connection query
	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host connection query: %1\n", bytes));
	
	if  (bytes.size() != 18) {
		cerr << "expecting 18 bytes, read " << bytes << " from " << _port->input_port().name() << endl;
		return response;
	}

	// build and send host connection reply
	response << 0x02;
	copy (bytes.begin() + 6, bytes.begin() + 6 + 7, back_inserter (response));
	response << calculate_challenge_response (bytes.begin() + 6 + 7, bytes.begin() + 6 + 7 + 4);
	return response;
}

// not used right now
MidiByteArray 
Surface::host_connection_confirmation (const MidiByteArray & bytes)
{
	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host_connection_confirmation: %1\n", bytes));
	
	// decode host connection confirmation
	if  (bytes.size() != 14) {
		ostringstream os;
		os << "expecting 14 bytes, read " << bytes << " from " << _port->input_port().name();
		throw MackieControlException (os.str());
	}
	
	// send version request
	return MidiByteArray (2, 0x13, 0x00);
}

void
Surface::turn_it_on ()
{
	if (_active) {
		return;
	}

	_active = true;

	_mcp.device_ready ();

	for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->notify_all ();
	}

	update_view_mode_display ();

	if (_mcp.device_info ().has_global_controls ()) {
		_mcp.update_global_button (Button::Read, _mcp.metering_active ());
	}
}

void 
Surface::write_sysex (const MidiByteArray & mba)
{
	if (mba.empty()) {
		return;
	}

	MidiByteArray buf;
	buf << sysex_hdr() << mba << MIDI::eox;
	_port->write (buf);
}

void 
Surface::write_sysex (MIDI::byte msg)
{
	MidiByteArray buf;
	buf << sysex_hdr() << msg << MIDI::eox;
	_port->write (buf);
}

uint32_t
Surface::n_strips (bool with_locked_strips) const
{
	if (with_locked_strips) {
		return strips.size();
	} 

	uint32_t n = 0;

	for (Strips::const_iterator it = strips.begin(); it != strips.end(); ++it) {
		if (!(*it)->locked()) {
			++n;
		}
	}
	return n;
}

Strip*
Surface::nth_strip (uint32_t n) const
{
	if (n > n_strips()) {
		return 0;
	}
	return strips[n];
}

void
Surface::zero_all ()
{
	if (_mcp.device_info().has_timecode_display ()) {
		display_timecode (string (10, '0'), string (10, ' '));
	}
	
	if (_mcp.device_info().has_two_character_display()) {
		show_two_char_display (string (2, '0'), string (2, ' '));
	}

	if (_mcp.device_info().has_master_fader () && _master_fader) {
		_port->write (_master_fader->zero ());
	}

	// zero all strips
	for (Strips::iterator it = strips.begin(); it != strips.end(); ++it) {
		(*it)->zero();
	}

	zero_controls ();
}

void
Surface::zero_controls ()
{
	if (!_mcp.device_info().has_global_controls()) {
		return;
	}

	// turn off global buttons and leds

	for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
		Control & control = **it;
		if (!control.group().is_strip()) {
			_port->write (control.zero());
		}
	}

	// and the led ring for the master strip
	blank_jog_ring ();

	_last_master_gain_written = 0.0f;
}

void
Surface::periodic (uint64_t now_usecs)
{
	master_gain_changed();
	for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->periodic (now_usecs);
	}
}

void
Surface::redisplay ()
{
	for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->redisplay ();
	}
}

void
Surface::write (const MidiByteArray& data) 
{
	if (_active) {
		_port->write (data);
	} else {
		DEBUG_TRACE (DEBUG::MackieControl, "surface not active, write ignored\n");
	}
}

void
Surface::map_routes (const vector<boost::shared_ptr<Route> >& routes)
{
	vector<boost::shared_ptr<Route> >::const_iterator r;
	Strips::iterator s = strips.begin();

	DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mapping %1 routes\n", routes.size()));

	for (r = routes.begin(); r != routes.end() && s != strips.end(); ++s) {

		/* don't try to assign routes to a locked strip. it won't
		   use it anyway, but if we do, then we get out of sync
		   with the proposed mapping.
		*/

		if (!(*s)->locked()) {
			(*s)->set_route (*r);
			++r;
		}
	}

	for (; s != strips.end(); ++s) {
		(*s)->set_route (boost::shared_ptr<Route>());
	}


}

static char 
translate_seven_segment (char achar)
{
	achar = toupper (achar);

	if  (achar >= 0x40 && achar <= 0x60) {
		return achar - 0x40;
	} else if  (achar >= 0x21 && achar <= 0x3f) {
		return achar;
	} else {
		return 0x00;
	}
}

void
Surface::show_two_char_display (const std::string & msg, const std::string & dots)
{
	if (_stype != mcu || !_mcp.device_info().has_two_character_display() || msg.length() != 2 || dots.length() != 2) {
		return;
	}
	
	MidiByteArray right (3, 0xb0, 0x4b, 0x00);
	MidiByteArray left (3, 0xb0, 0x4a, 0x00);
	
	right[2] = translate_seven_segment (msg[0]) +  (dots[0] == '.' ? 0x40 : 0x00);
	left[2] = translate_seven_segment (msg[1]) +  (dots[1] == '.' ? 0x40 : 0x00);
	
	_port->write (right);
	_port->write (left);
}

void
Surface::show_two_char_display (unsigned int value, const std::string & /*dots*/)
{
	ostringstream os;
	os << setfill('0') << setw(2) << value % 100;
	show_two_char_display (os.str());
}

void
Surface::display_timecode (const std::string & timecode, const std::string & last_timecode)
{
	if (!_active || !_mcp.device_info().has_timecode_display()) {
		return;
	}
	// if there's no change, send nothing, not even sysex header
	if  (timecode == last_timecode) return;
	
	// length sanity checking
	string local_timecode = timecode;

	// truncate to 10 characters
	if  (local_timecode.length() > 10) {
		local_timecode = local_timecode.substr (0, 10);
	}

	// pad to 10 characters
	while  (local_timecode.length() < 10) { 
		local_timecode += " ";
	}
	
	// translate characters.
	// Only the characters that actually changed are sent.
	int position = 0x3f;
	int i;
	for (i = local_timecode.length () - 1; i >= 0; i--) {
		position++;
		if (local_timecode[i] == last_timecode[i]) {
			continue;
		}
		MidiByteArray retval (2, 0xb0, position);
		retval << translate_seven_segment (local_timecode[i]);
		_port->write (retval);
	}
}

void
Surface::update_flip_mode_display ()
{
	for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->flip_mode_changed (true);
	}
}

void
Surface::update_view_mode_display ()
{
	string text;
	int id = -1;

	if (!_active) {
		return;
	}

	switch (_mcp.view_mode()) {
	case MackieControlProtocol::Mixer:
		show_two_char_display ("Mx");
		id = Button::Pan;
		break;
	case MackieControlProtocol::Dynamics:
		show_two_char_display ("Dy");
		id = Button::Dyn;
		break;
	case MackieControlProtocol::EQ:
		show_two_char_display ("EQ");
		id = Button::Eq;
		break;
	case MackieControlProtocol::Loop:
		show_two_char_display ("LP");
		id = Button::Loop;
		break;
	case MackieControlProtocol::AudioTracks:
		show_two_char_display ("AT");
		break;
	case MackieControlProtocol::MidiTracks:
		show_two_char_display ("MT");
		break;
	case MackieControlProtocol::Sends:
		show_two_char_display ("Sn");
		id = Button::Send;
		break;
	case MackieControlProtocol::Plugins:
		show_two_char_display ("Pl");
		id = Button::Plugin;
		break;
	default:
		break;
	}

	if (id >= 0) {
		
		/* we are attempting to turn a global button/LED on */

		map<int,Control*>::iterator x = controls_by_device_independent_id.find (id);

		if (x != controls_by_device_independent_id.end()) {
			Button* button = dynamic_cast<Button*> (x->second);
			if (button) {
				_port->write (button->set_state (on));
			}
		}
	}

	if (!text.empty()) {
		for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
			_port->write ((*s)->display (1, text));
		}
	}
}

void
Surface::gui_selection_changed (const ARDOUR::StrongRouteNotificationList& routes)
{
	for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->gui_selection_changed (routes);
	}
}

void
Surface::say_hello ()
{
	/* wakeup for Mackie Control */
	MidiByteArray wakeup (7, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x00, MIDI::eox);
	_port->write (wakeup);
	wakeup[4] = 0x15; /* wakup Mackie XT */
	_port->write (wakeup);
	wakeup[4] = 0x10; /* wakeup Logic Control */
	_port->write (wakeup);
	wakeup[4] = 0x11; /* wakeup Logic Control XT */
	_port->write (wakeup);
}

void
Surface::next_jog_mode ()
{
}

void
Surface::set_jog_mode (JogWheel::Mode)
{
}	

bool
Surface::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
{
	for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
		if ((*s)->route() == r && (*s)->locked()) {
			return true;
		}
	}
	return false;
}

void 
Surface::notify_metering_state_changed()
{
	for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
		(*s)->notify_metering_state_changed ();
	}
}

void
Surface::reset ()
{
	if (_port) {
		/* reset msg for Mackie Control */
		MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x08, 0x00, MIDI::eox);
		_port->write (msg); 
		msg[4] = 0x15; /* reset Mackie XT */
		_port->write (msg);
		msg[4] = 0x10; /* reset Logic Control */
		_port->write (msg);
		msg[4] = 0x11; /* reset Logic Control XT */
		_port->write (msg);
	}
}

void
Surface::toggle_backlight ()
{
	if (_port) {
		int onoff = random() %2;
		MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x0a, onoff, MIDI::eox);
		_port->write (msg); 
		msg[4] = 0x15; /* reset Mackie XT */
		_port->write (msg);
		msg[4] = 0x10; /* reset Logic Control */
		_port->write (msg);
		msg[4] = 0x11; /* reset Logic Control XT */
		_port->write (msg);
	}
}

void
Surface::recalibrate_faders ()
{
	if (_port) {
		MidiByteArray msg (8, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x09, 0x00, MIDI::eox);
		_port->write (msg); 
		msg[4] = 0x15; /* reset Mackie XT */
		_port->write (msg);
		msg[4] = 0x10; /* reset Logic Control */
		_port->write (msg);
		msg[4] = 0x11; /* reset Logic Control XT */
		_port->write (msg);
	}
}	

void
Surface::set_touch_sensitivity (int sensitivity)
{
	/* NOTE: assumed called from GUI code, hence sleep() */
	
	/* sensitivity already clamped by caller */

	if (_port) {
		MidiByteArray msg (9, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x0e, 0xff, sensitivity, MIDI::eox);

		for (int fader = 0; fader < 9; ++fader) {
			msg[6] = fader;

			_port->write (msg); 
			msg[4] = 0x15; /* reset Mackie XT */
			_port->write (msg);
			msg[4] = 0x10; /* reset Logic Control */
			_port->write (msg);
			msg[4] = 0x11; /* reset Logic Control XT */

			g_usleep (1000); /* milliseconds */
		}
	}
}