megaopus commit: (1) add __STD_(LIMIT|FORMAT)_MACROS to command line flags for cc...
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.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
19 #include <fcntl.h>
20 #include <iostream>
21 #include <algorithm>
22 #include <cmath>
23 #include <sstream>
24 #include <vector>
25 #include <iomanip>
26
27 #include <inttypes.h>
28 #include <float.h>
29 #include <sys/time.h>
30 #include <errno.h>
31 #include <poll.h>
32
33 #include <boost/shared_array.hpp>
34
35 #include "midi++/types.h"
36 #include "midi++/port.h"
37 #include "midi++/manager.h"
38 #include "pbd/pthread_utils.h"
39 #include "pbd/error.h"
40 #include "pbd/memento_command.h"
41 #include "pbd/convert.h"
42
43 #include "ardour/dB.h"
44 #include "ardour/debug.h"
45 #include "ardour/location.h"
46 #include "ardour/midi_ui.h"
47 #include "ardour/panner.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/types.h"
52 #include "ardour/audioengine.h"
53
54 #include "mackie_control_protocol.h"
55
56 #include "midi_byte_array.h"
57 #include "mackie_control_exception.h"
58 #include "route_signal.h"
59 #include "mackie_midi_builder.h"
60 #include "surface_port.h"
61 #include "surface.h"
62 #include "bcf_surface.h"
63 #include "mackie_surface.h"
64
65 using namespace ARDOUR;
66 using namespace std;
67 using namespace Mackie;
68 using namespace PBD;
69
70 using boost::shared_ptr;
71
72 #include "i18n.h"
73
74 MackieMidiBuilder builder;
75
76 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
77 #define ui_bind(f, ...) boost::protect (boost::bind (f, __VA_ARGS__))
78
79 MackieControlProtocol::MackieControlProtocol (Session& session)
80         : ControlProtocol (session, X_("Mackie"), MidiControlUI::instance())
81         , _current_initial_bank (0)
82         , _surface (0)
83         , _jog_wheel (*this)
84         , _timecode_type (ARDOUR::AnyTime::BBT)
85         , _input_bundle (new ARDOUR::Bundle (_("Mackie Control In"), true))
86         , _output_bundle (new ARDOUR::Bundle (_("Mackie Control Out"), false))
87 {
88         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
89 }
90
91 MackieControlProtocol::~MackieControlProtocol()
92 {
93         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol\n");
94
95         try {
96                 close();
97         }
98         catch (exception & e) {
99                 cout << "~MackieControlProtocol caught " << e.what() << endl;
100         }
101         catch (...) {
102                 cout << "~MackieControlProtocol caught unknown" << endl;
103         }
104
105         DEBUG_TRACE (DEBUG::MackieControl, "finished ~MackieControlProtocol::MackieControlProtocol\n");
106 }
107
108 Mackie::Surface& 
109 MackieControlProtocol::surface()
110 {
111         if (_surface == 0) {
112                 throw MackieControlException ("_surface is 0 in MackieControlProtocol::surface");
113         }
114         return *_surface;
115 }
116
117 const Mackie::SurfacePort& 
118 MackieControlProtocol::mcu_port() const
119 {
120         if (_ports.size() < 1) {
121                 return _dummy_port;
122         } else {
123                 return dynamic_cast<const MackiePort &> (*_ports[0]);
124         }
125 }
126
127 Mackie::SurfacePort& 
128 MackieControlProtocol::mcu_port()
129 {
130         if (_ports.size() < 1) {
131                 return _dummy_port;
132         } else {
133                 return dynamic_cast<MackiePort &> (*_ports[0]);
134         }
135 }
136
137 // go to the previous track.
138 // Assume that get_sorted_routes().size() > route_table.size()
139 void 
140 MackieControlProtocol::prev_track()
141 {
142         if (_current_initial_bank >= 1) {
143                 session->set_dirty();
144                 switch_banks (_current_initial_bank - 1);
145         }
146 }
147
148 // go to the next track.
149 // Assume that get_sorted_routes().size() > route_table.size()
150 void 
151 MackieControlProtocol::next_track()
152 {
153         Sorted sorted = get_sorted_routes();
154         if (_current_initial_bank + route_table.size() < sorted.size())
155         {
156                 session->set_dirty();
157                 switch_banks (_current_initial_bank + 1);
158         }
159 }
160
161 void 
162 MackieControlProtocol::clear_route_signals()
163 {
164         for (RouteSignals::iterator it = route_signals.begin(); it != route_signals.end(); ++it) {
165                 delete *it;
166         }
167         route_signals.clear();
168 }
169
170 // return the port for a given id - 0 based
171 // throws an exception if no port found
172 MackiePort& 
173 MackieControlProtocol::port_for_id (uint32_t index)
174 {
175         uint32_t current_max = 0;
176         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
177                 current_max += (*it)->strips();
178                 if (index < current_max) return **it;
179         }
180
181         // oops - no matching port
182         ostringstream os;
183         os << "No port for index " << index;
184         throw MackieControlException (os.str());
185 }
186
187 // predicate for sort call in get_sorted_routes
188 struct RouteByRemoteId
189 {
190         bool operator () (const shared_ptr<Route> & a, const shared_ptr<Route> & b) const
191         {
192                 return a->remote_control_id() < b->remote_control_id();
193         }
194
195         bool operator () (const Route & a, const Route & b) const
196         {
197                 return a.remote_control_id() < b.remote_control_id();
198         }
199
200         bool operator () (const Route * a, const Route * b) const
201         {
202                 return a->remote_control_id() < b->remote_control_id();
203         }
204 };
205
206 MackieControlProtocol::Sorted 
207 MackieControlProtocol::get_sorted_routes()
208 {
209         Sorted sorted;
210
211         // fetch all routes
212         boost::shared_ptr<RouteList> routes = session->get_routes();
213         set<uint32_t> remote_ids;
214
215         // routes with remote_id 0 should never be added
216         // TODO verify this with ardour devs
217         // remote_ids.insert (0);
218
219         // sort in remote_id order, and exclude master, control and hidden routes
220         // and any routes that are already set.
221         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it)
222         {
223                 Route & route = **it;
224                 if (
225                                 route.active()
226                                 && !route.is_master()
227                                 && !route.is_hidden()
228                                 && !route.is_monitor()
229                                 && remote_ids.find (route.remote_control_id()) == remote_ids.end()
230                 )
231                 {
232                         sorted.push_back (*it);
233                         remote_ids.insert (route.remote_control_id());
234                 }
235         }
236         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
237         return sorted;
238 }
239
240 void 
241 MackieControlProtocol::refresh_current_bank()
242 {
243         switch_banks (_current_initial_bank);
244 }
245
246 void 
247 MackieControlProtocol::switch_banks (int initial)
248 {
249         // DON'T prevent bank switch if initial == _current_initial_bank
250         // because then this method can't be used as a refresh
251
252         // sanity checking
253         Sorted sorted = get_sorted_routes();
254         int delta = sorted.size() - route_table.size();
255         if (initial < 0 || (delta > 0 && initial > delta))
256         {
257                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
258                 return;
259         }
260         _current_initial_bank = initial;
261
262         // first clear the signals from old routes
263         // taken care of by the RouteSignal destructors
264         clear_route_signals();
265
266         // now set the signals for new routes
267         if (_current_initial_bank <= sorted.size())
268         {
269                 // fetch the bank start and end to switch to
270                 uint32_t end_pos = min (route_table.size(), sorted.size());
271                 Sorted::iterator it = sorted.begin() + _current_initial_bank;
272                 Sorted::iterator end = sorted.begin() + _current_initial_bank + end_pos;
273
274                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2\n", _current_initial_bank, end_pos));
275
276                 // link routes to strips
277                 uint32_t i = 0;
278                 for (; it != end && it != sorted.end(); ++it, ++i)
279                 {
280                         boost::shared_ptr<Route> route = *it;
281
282                         assert (surface().strips[i]);
283                         Strip & strip = *surface().strips[i];
284
285                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("remote id %1 connecting %2 to %3 with port %4\n", 
286                                                                            route->remote_control_id(), route->name(), strip.name(), port_for_id(i)));
287                         route_table[i] = route;
288                         RouteSignal * rs = new RouteSignal (route, *this, strip, port_for_id(i));
289                         route_signals.push_back (rs);
290                         // update strip from route
291                         rs->notify_all();
292                 }
293
294                 // create dead strips if there aren't enough routes to
295                 // fill a bank
296                 for (; i < route_table.size(); ++i)
297                 {
298                         Strip & strip = *surface().strips[i];
299                         // send zero for this strip
300                         MackiePort & port = port_for_id(i);
301                         port.write (builder.zero_strip (port, strip));
302                 }
303         }
304
305         // display the current start bank.
306         surface().display_bank_start (mcu_port(), builder, _current_initial_bank);
307 }
308
309 void 
310 MackieControlProtocol::zero_all()
311 {
312         // TODO turn off Timecode displays
313
314         // zero all strips
315         for (Surface::Strips::iterator it = surface().strips.begin(); it != surface().strips.end(); ++it)
316         {
317                 MackiePort & port = port_for_id ((*it)->index());
318                 port.write (builder.zero_strip (port, **it));
319         }
320
321         // and the master strip
322         mcu_port().write (builder.zero_strip (dynamic_cast<MackiePort&> (mcu_port()), master_strip()));
323
324         // turn off global buttons and leds
325         // global buttons are only ever on mcu_port, so we don't have
326         // to figure out which port.
327         for (Surface::Controls::iterator it = surface().controls.begin(); it != surface().controls.end(); ++it)
328         {
329                 Control & control = **it;
330                 if (!control.group().is_strip() && control.accepts_feedback())
331                 {
332                         mcu_port().write (builder.zero_control (control));
333                 }
334         }
335
336         // any hardware-specific stuff
337         surface().zero_all (mcu_port(), builder);
338 }
339
340 int 
341 MackieControlProtocol::set_active (bool yn)
342 {
343         if (yn != _active)
344         {
345                 try
346                 {
347                         // the reason for the locking and unlocking is that
348                         // glibmm can't do a condition wait on a RecMutex
349                         if (yn)
350                         {
351                                 // TODO what happens if this fails half way?
352
353                                 // create MackiePorts
354                                 {
355                                         Glib::Mutex::Lock lock (update_mutex);
356                                         create_ports();
357                                 }
358
359                                 // now initialise MackiePorts - ie exchange sysex messages
360                                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
361                                         (*it)->open();
362                                 }
363
364                                 // wait until all ports are active
365                                 // TODO a more sophisticated approach would
366                                 // allow things to start up with only an MCU, even if
367                                 // extenders were specified but not responding.
368                                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
369                                         (*it)->wait_for_init();
370                                 }
371
372                                 // create surface object. This depends on the ports being
373                                 // correctly initialised
374                                 initialize_surface();
375                                 connect_session_signals();
376
377                                 // yeehah!
378                                 _active = true;
379
380                                 // send current control positions to surface
381                                 // must come after _active = true otherwise it won't run
382                                 update_surface();
383                         } else {
384                                 close();
385                                 _active = false;
386                         }
387                 }
388
389                 catch (exception & e) {
390                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("set_active to false because exception caught: %1\n", e.what()));
391                         _active = false;
392                         throw;
393                 }
394         }
395
396         return 0;
397 }
398
399 bool 
400 MackieControlProtocol::handle_strip_button (Control & control, ButtonState bs, boost::shared_ptr<Route> route)
401 {
402         bool state = false;
403
404         if (bs == press)
405         {
406                 if (control.name() == "recenable")
407                 {
408                         state = !route->record_enabled();
409                         route->set_record_enabled (state, this);
410                 }
411                 else if (control.name() == "mute")
412                 {
413                         state = !route->muted();
414                         route->set_mute (state, this);
415                 }
416                 else if (control.name() == "solo")
417                 {
418                         state = !route->soloed();
419                         route->set_solo (state, this);
420                 }
421                 else if (control.name() == "select")
422                 {
423                         // TODO make the track selected. Whatever that means.
424                         //state = default_button_press (dynamic_cast<Button&> (control));
425                 }
426                 else if (control.name() == "vselect")
427                 {
428                         // TODO could be used to select different things to apply the pot to?
429                         //state = default_button_press (dynamic_cast<Button&> (control));
430                 }
431         }
432
433         if (control.name() == "fader_touch")
434         {
435                 state = bs == press;
436                 control.strip().gain().in_use (state);
437         }
438
439         return state;
440 }
441
442 void 
443 MackieControlProtocol::update_led (Mackie::Button & button, Mackie::LedState ls)
444 {
445         if (ls != none)
446         {
447                 SurfacePort * port = 0;
448                 if (button.group().is_strip())
449                 {
450                         if (button.group().is_master())
451                         {
452                                 port = &mcu_port();
453                         }
454                         else
455                         {
456                                 port = &port_for_id (dynamic_cast<const Strip&> (button.group()).index());
457                         }
458                 }
459                 else
460                 {
461                         port = &mcu_port();
462                 }
463                 port->write (builder.build_led (button, ls));
464         }
465 }
466
467 void 
468 MackieControlProtocol::update_timecode_beats_led()
469 {
470         switch (_timecode_type)
471         {
472                 case ARDOUR::AnyTime::BBT:
473                         update_global_led ("beats", on);
474                         update_global_led ("timecode", off);
475                         break;
476                 case ARDOUR::AnyTime::Timecode:
477                         update_global_led ("timecode", on);
478                         update_global_led ("beats", off);
479                         break;
480                 default:
481                         ostringstream os;
482                         os << "Unknown Anytime::Type " << _timecode_type;
483                         throw runtime_error (os.str());
484         }
485 }
486
487 void 
488 MackieControlProtocol::update_global_button (const string & name, LedState ls)
489 {
490         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
491         {
492                 Button * button = dynamic_cast<Button*> (surface().controls_by_name[name]);
493                 mcu_port().write (builder.build_led (button->led(), ls));
494         }
495         else
496         {
497                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", name));
498         }
499 }
500
501 void 
502 MackieControlProtocol::update_global_led (const string & name, LedState ls)
503 {
504         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
505         {
506                 Led * led = dynamic_cast<Led*> (surface().controls_by_name[name]);
507                 mcu_port().write (builder.build_led (*led, ls));
508         }
509         else
510         {
511                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", name));
512         }
513 }
514
515 // send messages to surface to set controls to correct values
516 void 
517 MackieControlProtocol::update_surface()
518 {
519         if (_active)
520         {
521                 // do the initial bank switch to connect signals
522                 // _current_initial_bank is initialised by set_state
523                 switch_banks (_current_initial_bank);
524
525                 // create a RouteSignal for the master route
526
527  boost::shared_ptr<Route> mr = master_route ();
528  if (mr) {
529  master_route_signal = shared_ptr<RouteSignal> (new RouteSignal (mr, *this, master_strip(), mcu_port()));
530  // update strip from route
531  master_route_signal->notify_all();
532  }
533
534                 // sometimes the jog wheel is a pot
535                 surface().blank_jog_ring (mcu_port(), builder);
536
537                 // update global buttons and displays
538                 notify_record_state_changed();
539                 notify_transport_state_changed();
540                 update_timecode_beats_led();
541         }
542 }
543
544 void 
545 MackieControlProtocol::connect_session_signals()
546 {
547         // receive routes added
548         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_route_added, this, _1), midi_ui_context());
549         // receive record state toggled
550         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_record_state_changed, this), midi_ui_context());
551         // receive transport state changed
552         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_transport_state_changed, this), midi_ui_context());
553         // receive punch-in and punch-out
554         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
555         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
556         // receive rude solo changed
557         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), midi_ui_context());
558
559         // make sure remote id changed signals reach here
560         // see also notify_route_added
561         Sorted sorted = get_sorted_routes();
562
563         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
564                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind(&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
565         }
566 }
567
568 void 
569 MackieControlProtocol::add_port (MIDI::Port & midi_input_port, MIDI::Port & midi_output_port, int number)
570 {
571         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("add port %1 %2\n", midi_input_port.name(), midi_output_port.name()));
572
573         MackiePort * sport = new MackiePort (*this, midi_input_port, midi_output_port, number);
574         _ports.push_back (sport);
575         
576         sport->init_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_init, this, sport));
577         sport->active_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_active, this, sport));
578         sport->inactive_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_inactive, this, sport));
579
580         _input_bundle->add_channel (
581                 midi_input_port.name(),
582                 ARDOUR::DataType::MIDI,
583                 session->engine().make_port_name_non_relative (midi_input_port.name())
584                 );
585         
586         _output_bundle->add_channel (
587                 midi_output_port.name(),
588                 ARDOUR::DataType::MIDI,
589                 session->engine().make_port_name_non_relative (midi_output_port.name())
590                 );
591 }
592
593 void 
594 MackieControlProtocol::create_ports()
595 {
596         MIDI::Manager * mm = MIDI::Manager::instance();
597         MIDI::Port * midi_input_port = mm->add_port (
598                 new MIDI::Port (string_compose (_("%1 in"), default_port_name), MIDI::Port::IsInput, session->engine().jack())
599                 );
600         MIDI::Port * midi_output_port = mm->add_port (
601                 new MIDI::Port (string_compose (_("%1 out"), default_port_name), MIDI::Port::IsOutput, session->engine().jack())
602                 );
603
604         // open main port               
605
606         if (!midi_input_port->ok() || !midi_output_port->ok()) {
607                 ostringstream os;
608                 os << _("Mackie control MIDI ports could not be created; Mackie control disabled");
609                 error << os.str() << endmsg;
610                 throw MackieControlException (os.str());
611         }
612
613         add_port (*midi_input_port, *midi_output_port, 0);
614
615         // open extender ports. Up to 9. Should be enough.
616         // could also use mm->get_midi_ports()
617
618         for (int index = 1; index <= 9; ++index) {
619                 MIDI::Port * midi_input_port = mm->add_port (
620                         new MIDI::Port (string_compose (_("mcu_xt_%1 in"), index), MIDI::Port::IsInput, session->engine().jack())
621                         );
622                 MIDI::Port * midi_output_port = mm->add_port (
623                         new MIDI::Port (string_compose (_("mcu_xt_%1 out"), index), MIDI::Port::IsOutput, session->engine().jack())
624                         );
625                 if (midi_input_port->ok() && midi_output_port->ok()) {
626                         add_port (*midi_input_port, *midi_output_port, index);
627                 }
628         }
629 }
630
631 shared_ptr<Route> 
632 MackieControlProtocol::master_route()
633 {
634         return session->master_out ();
635 }
636
637 Strip& 
638 MackieControlProtocol::master_strip()
639 {
640         return dynamic_cast<Strip&> (*surface().groups["master"]);
641 }
642
643 void 
644 MackieControlProtocol::initialize_surface()
645 {
646         // set up the route table
647         int strips = 0;
648         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
649                 strips += (*it)->strips();
650         }
651
652         set_route_table_size (strips);
653
654         // TODO same as code in mackie_port.cc
655         string emulation = ARDOUR::Config->get_mackie_emulation();
656         if (emulation == "bcf")
657         {
658                 _surface = new BcfSurface (strips);
659         }
660         else if (emulation == "mcu")
661         {
662                 _surface = new MackieSurface (strips);
663         }
664         else
665         {
666                 ostringstream os;
667                 os << "no Surface class found for emulation: " << emulation;
668                 throw MackieControlException (os.str());
669         }
670
671         _surface->init();
672
673         // Connect events. Must be after route table otherwise there will be trouble
674
675         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
676                 (*it)->control_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_control_event, this, _1, _2, _3));
677         }
678 }
679
680 void 
681 MackieControlProtocol::close()
682 {
683
684         // must be before other shutdown otherwise polling loop
685         // calls methods on objects that are deleted
686
687         port_connections.drop_connections ();
688         session_connections.drop_connections ();
689         route_connections.drop_connections ();
690
691         if (_surface != 0) {
692                 // These will fail if the port has gone away.
693                 // So catch the exception and do the rest of the
694                 // close afterwards
695                 // because the bcf doesn't respond to the next 3 sysex messages
696                 try {
697                         zero_all();
698                 }
699
700                 catch (exception & e) {
701                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
702                 }
703
704                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
705                         try {
706                                 MackiePort & port = **it;
707                                 // faders to minimum
708                                 port.write_sysex (0x61);
709                                 // All LEDs off
710                                 port.write_sysex (0x62);
711                                 // Reset (reboot into offline mode)
712                                 port.write_sysex (0x63);
713                         }
714                         catch (exception & e) {
715                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
716                         }
717                 }
718
719                 // disconnect routes from strips
720                 clear_route_signals();
721                 delete _surface;
722                 _surface = 0;
723         }
724
725         // shut down MackiePorts
726         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
727                 delete *it;
728         }
729
730         _ports.clear();
731 }
732
733 XMLNode& 
734 MackieControlProtocol::get_state()
735 {
736         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state\n");
737
738         // add name of protocol
739         XMLNode* node = new XMLNode (X_("Protocol"));
740         node->add_property (X_("name"), _name);
741
742         // add current bank
743         ostringstream os;
744         os << _current_initial_bank;
745         node->add_property (X_("bank"), os.str());
746
747         return *node;
748 }
749
750 int 
751 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
752 {
753         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
754
755         int retval = 0;
756
757         // fetch current bank
758
759         if (node.property (X_("bank")) != 0) {
760                 string bank = node.property (X_("bank"))->value();
761                 try {
762                         set_active (true);
763                         uint32_t new_bank = atoi (bank.c_str());
764                         if (_current_initial_bank != new_bank) {
765                                 switch_banks (new_bank);
766                         }
767                 }
768                 catch (exception & e) {
769                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("exception in MackieControlProtocol::set_state: %1\n", e.what()));
770                         return -1;
771                 }
772         }
773
774         return retval;
775 }
776
777 void 
778 MackieControlProtocol::handle_control_event (SurfacePort & port, Control & control, const ControlState & state)
779 {
780         // find the route for the control, if there is one
781         boost::shared_ptr<Route> route;
782         if (control.group().is_strip()) {
783                 if (control.group().is_master()) {
784                         route = master_route();
785                 } else {
786                         uint32_t index = control.ordinal() - 1 + (port.number() * port.strips());
787                         if (index < route_table.size())
788                                 route = route_table[index];
789                         else
790                                 cerr << "Warning: index is " << index << " which is not in the route table, size: " << route_table.size() << endl;
791                 }
792         }
793
794         // This handles control element events from the surface
795         // the state of the controls on the surface is usually updated
796         // from UI events.
797         switch (control.type()) {
798                 case Control::type_fader:
799                         // find the route in the route table for the id
800                         // if the route isn't available, skip it
801                         // at which point the fader should just reset itself
802                         if (route != 0)
803                         {
804                                 route->gain_control()->set_value (state.pos);
805
806                                 // must echo bytes back to slider now, because
807                                 // the notifier only works if the fader is not being
808                                 // touched. Which it is if we're getting input.
809                                 port.write (builder.build_fader ((Fader&)control, state.pos));
810                         }
811                         break;
812
813                 case Control::type_button:
814                         if (control.group().is_strip()) {
815                                 // strips
816                                 if (route != 0) {
817                                         handle_strip_button (control, state.button_state, route);
818                                 } else {
819                                         // no route so always switch the light off
820                                         // because no signals will be emitted by a non-route
821                                         port.write (builder.build_led (control.led(), off));
822                                 }
823                         } else if (control.group().is_master()) {
824                                 // master fader touch
825                                 if (route != 0) {
826                                         handle_strip_button (control, state.button_state, route);
827                                 }
828                         } else {
829                                 // handle all non-strip buttons
830                                 surface().handle_button (*this, state.button_state, dynamic_cast<Button&> (control));
831                         }
832                         break;
833
834                 // pot (jog wheel, external control)
835                 case Control::type_pot:
836                         if (control.group().is_strip()) {
837                                 if (route != 0 && route->panner())
838                                 {
839                                         // pan for mono input routes, or stereo linked panners
840                                         if (route->panner()->npanners() == 1 || (route->panner()->npanners() == 2 && route->panner()->linked()))
841                                         {
842                                                 // assume pan for now
843                                                 float xpos;
844                                                 route->panner()->streampanner (0).get_effective_position (xpos);
845
846                                                 // calculate new value, and trim
847                                                 xpos += state.delta * state.sign;
848                                                 if (xpos > 1.0)
849                                                         xpos = 1.0;
850                                                 else if (xpos < 0.0)
851                                                         xpos = 0.0;
852
853                                                 route->panner()->streampanner (0).set_position (xpos);
854                                         }
855                                 }
856                                 else
857                                 {
858                                         // it's a pot for an umnapped route, so turn all the lights off
859                                         port.write (builder.build_led_ring (dynamic_cast<Pot &> (control), off));
860                                 }
861                         }
862                         else
863                         {
864                                 if (control.is_jog())
865                                 {
866                                         _jog_wheel.jog_event (port, control, state);
867                                 }
868                                 else
869                                 {
870                                         cout << "external controller" << state.ticks * state.sign << endl;
871                                 }
872                         }
873                         break;
874
875                 default:
876                         cout << "Control::type not handled: " << control.type() << endl;
877         }
878 }
879
880 /////////////////////////////////////////////////
881 // handlers for Route signals
882 // TODO should these be part of RouteSignal?
883 // They started off as signal/slot handlers for signals
884 // from Route, but they're also used in polling for automation
885 /////////////////////////////////////////////////
886
887 void 
888 MackieControlProtocol::notify_solo_changed (RouteSignal * route_signal)
889 {
890         try
891         {
892                 Button & button = route_signal->strip().solo();
893                 route_signal->port().write (builder.build_led (button, route_signal->route()->soloed()));
894         }
895         catch (exception & e)
896         {
897                 cout << e.what() << endl;
898         }
899 }
900
901 void 
902 MackieControlProtocol::notify_mute_changed (RouteSignal * route_signal)
903 {
904         try
905         {
906                 Button & button = route_signal->strip().mute();
907                 route_signal->port().write (builder.build_led (button, route_signal->route()->muted()));
908         }
909         catch (exception & e)
910         {
911                 cout << e.what() << endl;
912         }
913 }
914
915 void 
916 MackieControlProtocol::notify_record_enable_changed (RouteSignal * route_signal)
917 {
918         try
919         {
920                 Button & button = route_signal->strip().recenable();
921                 route_signal->port().write (builder.build_led (button, route_signal->route()->record_enabled()));
922         }
923         catch (exception & e)
924         {
925                 cout << e.what() << endl;
926         }
927 }
928
929 void MackieControlProtocol::notify_active_changed (RouteSignal *)
930 {
931         try
932         {
933                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::notify_active_changed\n");
934                 refresh_current_bank();
935         }
936         catch (exception & e)
937         {
938                 cout << e.what() << endl;
939         }
940 }
941
942 void 
943 MackieControlProtocol::notify_gain_changed (RouteSignal * route_signal, bool force_update)
944 {
945         try
946         {
947                 Fader & fader = route_signal->strip().gain();
948                 if (!fader.in_use())
949                 {
950                         float gain_value = route_signal->route()->gain_control()->get_value();
951                         // check that something has actually changed
952                         if (force_update || gain_value != route_signal->last_gain_written())
953                         {
954                                 route_signal->port().write (builder.build_fader (fader, gain_value));
955                                 route_signal->last_gain_written (gain_value);
956                         }
957                 }
958         }
959         catch (exception & e)
960         {
961                 cout << e.what() << endl;
962         }
963 }
964
965 void 
966 MackieControlProtocol::notify_property_changed (const PropertyChange& what_changed, RouteSignal * route_signal)
967 {
968         if (!what_changed.contains (Properties::name)) {
969                 return;
970         }
971
972         try
973         {
974                 Strip & strip = route_signal->strip();
975                 
976                 /* XXX: not sure about this check to only display stuff for strips of index < 8 */
977                 if (!strip.is_master() && strip.index() < 8)
978                 {
979                         string line1;
980                         string fullname = route_signal->route()->name();
981
982                         if (fullname.length() <= 6)
983                         {
984                                 line1 = fullname;
985                         }
986                         else
987                         {
988                                 line1 = PBD::short_version (fullname, 6);
989                         }
990
991                         SurfacePort & port = route_signal->port();
992                         port.write (builder.strip_display (port, strip, 0, line1));
993                         port.write (builder.strip_display_blank (port, strip, 1));
994                 }
995         }
996         catch (exception & e)
997         {
998                 cout << e.what() << endl;
999         }
1000 }
1001
1002 void 
1003 MackieControlProtocol::notify_panner_changed (RouteSignal * route_signal, bool force_update)
1004 {
1005         try
1006         {
1007                 Pot & pot = route_signal->strip().vpot();
1008                 boost::shared_ptr<Panner> panner = route_signal->route()->panner();
1009                 if ((panner && panner->npanners() == 1) || (panner->npanners() == 2 && panner->linked()))
1010                 {
1011                         float pos;
1012                         route_signal->route()->panner()->streampanner(0).get_effective_position (pos);
1013
1014                         // cache the MidiByteArray here, because the mackie led control is much lower
1015                         // resolution than the panner control. So we save lots of byte
1016                         // sends in spite of more work on the comparison
1017                         MidiByteArray bytes = builder.build_led_ring (pot, ControlState (on, pos), MackieMidiBuilder::midi_pot_mode_dot);
1018                         // check that something has actually changed
1019                         if (force_update || bytes != route_signal->last_pan_written())
1020                         {
1021                                 route_signal->port().write (bytes);
1022                                 route_signal->last_pan_written (bytes);
1023                         }
1024                 }
1025                 else
1026                 {
1027                         route_signal->port().write (builder.zero_control (pot));
1028                 }
1029         }
1030         catch (exception & e)
1031         {
1032                 cout << e.what() << endl;
1033         }
1034 }
1035
1036 // TODO handle plugin automation polling
1037 void 
1038 MackieControlProtocol::update_automation (RouteSignal & rs)
1039 {
1040         ARDOUR::AutoState gain_state = rs.route()->gain_control()->automation_state();
1041
1042         if (gain_state == Touch || gain_state == Play)
1043         {
1044                 notify_gain_changed (&rs, false);
1045         }
1046
1047         if (rs.route()->panner()) {
1048                 ARDOUR::AutoState panner_state = rs.route()->panner()->automation_state();
1049                 if (panner_state == Touch || panner_state == Play)
1050                 {
1051                         notify_panner_changed (&rs, false);
1052                 }
1053         }
1054 }
1055
1056 string 
1057 MackieControlProtocol::format_bbt_timecode (nframes_t now_frame)
1058 {
1059         BBT_Time bbt_time;
1060         session->bbt_time (now_frame, bbt_time);
1061
1062         // According to the Logic docs
1063         // digits: 888/88/88/888
1064         // BBT mode: Bars/Beats/Subdivisions/Ticks
1065         ostringstream os;
1066         os << setw(3) << setfill('0') << bbt_time.bars;
1067         os << setw(2) << setfill('0') << bbt_time.beats;
1068
1069         // figure out subdivisions per beat
1070         const Meter & meter = session->tempo_map().meter_at (now_frame);
1071         int subdiv = 2;
1072         if (meter.note_divisor() == 8 && (meter.beats_per_bar() == 12.0 || meter.beats_per_bar() == 9.0 || meter.beats_per_bar() == 6.0))
1073         {
1074                 subdiv = 3;
1075         }
1076
1077         uint32_t subdivisions = bbt_time.ticks / uint32_t (Meter::ticks_per_beat / subdiv);
1078         uint32_t ticks = bbt_time.ticks % uint32_t (Meter::ticks_per_beat / subdiv);
1079
1080         os << setw(2) << setfill('0') << subdivisions + 1;
1081         os << setw(3) << setfill('0') << ticks;
1082
1083         return os.str();
1084 }
1085
1086 string 
1087 MackieControlProtocol::format_timecode_timecode (nframes_t now_frame)
1088 {
1089         Timecode::Time timecode;
1090         session->timecode_time (now_frame, timecode);
1091
1092         // According to the Logic docs
1093         // digits: 888/88/88/888
1094         // Timecode mode: Hours/Minutes/Seconds/Frames
1095         ostringstream os;
1096         os << setw(3) << setfill('0') << timecode.hours;
1097         os << setw(2) << setfill('0') << timecode.minutes;
1098         os << setw(2) << setfill('0') << timecode.seconds;
1099         os << setw(3) << setfill('0') << timecode.frames;
1100
1101         return os.str();
1102 }
1103
1104 void 
1105 MackieControlProtocol::update_timecode_display()
1106 {
1107         if (surface().has_timecode_display())
1108         {
1109                 // do assignment here so current_frame is fixed
1110                 nframes_t current_frame = session->transport_frame();
1111                 string timecode;
1112
1113                 switch (_timecode_type)
1114                 {
1115                         case ARDOUR::AnyTime::BBT:
1116                                 timecode = format_bbt_timecode (current_frame);
1117                                 break;
1118                         case ARDOUR::AnyTime::Timecode:
1119                                 timecode = format_timecode_timecode (current_frame);
1120                                 break;
1121                         default:
1122                                 ostringstream os;
1123                                 os << "Unknown timecode: " << _timecode_type;
1124                                 throw runtime_error (os.str());
1125                 }
1126
1127                 // only write the timecode string to the MCU if it's changed
1128                 // since last time. This is to reduce midi bandwidth used.
1129                 if (timecode != _timecode_last)
1130                 {
1131                         surface().display_timecode (mcu_port(), builder, timecode, _timecode_last);
1132                         _timecode_last = timecode;
1133                 }
1134         }
1135 }
1136
1137 void 
1138 MackieControlProtocol::poll_session_data()
1139 {
1140         // XXX need to attach this to a timer in the MIDI UI event loop (20msec)
1141
1142         if (_active) {
1143                 // do all currently mapped routes
1144                 for (RouteSignals::iterator it = route_signals.begin(); it != route_signals.end(); ++it) {
1145                         update_automation (**it);
1146                 }
1147
1148                 // and the master strip
1149                 if (master_route_signal != 0) {
1150                         update_automation (*master_route_signal);
1151                 }
1152
1153                 update_timecode_display();
1154         }
1155 }
1156
1157 /////////////////////////////////////
1158 // Transport Buttons
1159 /////////////////////////////////////
1160
1161 LedState 
1162 MackieControlProtocol::frm_left_press (Button &)
1163 {
1164         // can use first_mark_before/after as well
1165         unsigned long elapsed = _frm_left_last.restart();
1166
1167         Location * loc = session->locations()->first_location_before (
1168                 session->transport_frame()
1169         );
1170
1171         // allow a quick double to go past a previous mark
1172         if (session->transport_rolling() && elapsed < 500 && loc != 0)
1173         {
1174                 Location * loc_two_back = session->locations()->first_location_before (loc->start());
1175                 if (loc_two_back != 0)
1176                 {
1177                         loc = loc_two_back;
1178                 }
1179         }
1180
1181         // move to the location, if it's valid
1182         if (loc != 0)
1183         {
1184                 session->request_locate (loc->start(), session->transport_rolling());
1185         }
1186
1187         return on;
1188 }
1189
1190 LedState 
1191 MackieControlProtocol::frm_left_release (Button &)
1192 {
1193         return off;
1194 }
1195
1196 LedState 
1197 MackieControlProtocol::frm_right_press (Button &)
1198 {
1199         // can use first_mark_before/after as well
1200         Location * loc = session->locations()->first_location_after (
1201                 session->transport_frame()
1202         );
1203         if (loc != 0) session->request_locate (loc->start(), session->transport_rolling());
1204         return on;
1205 }
1206
1207 LedState 
1208 MackieControlProtocol::frm_right_release (Button &)
1209 {
1210         return off;
1211 }
1212
1213 LedState 
1214 MackieControlProtocol::stop_press (Button &)
1215 {
1216         session->request_stop();
1217         return on;
1218 }
1219
1220 LedState 
1221 MackieControlProtocol::stop_release (Button &)
1222 {
1223         return session->transport_stopped();
1224 }
1225
1226 LedState 
1227 MackieControlProtocol::play_press (Button &)
1228 {
1229         session->request_transport_speed (1.0);
1230         return on;
1231 }
1232
1233 LedState 
1234 MackieControlProtocol::play_release (Button &)
1235 {
1236         return session->transport_rolling();
1237 }
1238
1239 LedState 
1240 MackieControlProtocol::record_press (Button &)
1241 {
1242         if (session->get_record_enabled()) {
1243                 session->disable_record (false);
1244         } else {
1245                 session->maybe_enable_record();
1246         }
1247         return on;
1248 }
1249
1250 LedState 
1251 MackieControlProtocol::record_release (Button &)
1252 {
1253         if (session->get_record_enabled()) {
1254                 if (session->transport_rolling()) {
1255                         return on;
1256                 } else {
1257                         return flashing;
1258                 }
1259         } else {
1260                 return off;
1261         }
1262 }
1263
1264 LedState 
1265 MackieControlProtocol::rewind_press (Button &)
1266 {
1267         _jog_wheel.push (JogWheel::speed);
1268         _jog_wheel.transport_direction (-1);
1269         session->request_transport_speed (-_jog_wheel.transport_speed());
1270         return on;
1271 }
1272
1273 LedState 
1274 MackieControlProtocol::rewind_release (Button &)
1275 {
1276         _jog_wheel.pop();
1277         _jog_wheel.transport_direction (0);
1278         if (_transport_previously_rolling)
1279                 session->request_transport_speed (1.0);
1280         else
1281                 session->request_stop();
1282         return off;
1283 }
1284
1285 LedState 
1286 MackieControlProtocol::ffwd_press (Button &)
1287 {
1288         _jog_wheel.push (JogWheel::speed);
1289         _jog_wheel.transport_direction (1);
1290         session->request_transport_speed (_jog_wheel.transport_speed());
1291         return on;
1292 }
1293
1294 LedState 
1295 MackieControlProtocol::ffwd_release (Button &)
1296 {
1297         _jog_wheel.pop();
1298         _jog_wheel.transport_direction (0);
1299         if (_transport_previously_rolling)
1300                 session->request_transport_speed (1.0);
1301         else
1302                 session->request_stop();
1303         return off;
1304 }
1305
1306 LedState 
1307 MackieControlProtocol::loop_press (Button &)
1308 {
1309         session->request_play_loop (!session->get_play_loop());
1310         return on;
1311 }
1312
1313 LedState 
1314 MackieControlProtocol::loop_release (Button &)
1315 {
1316         return session->get_play_loop();
1317 }
1318
1319 LedState 
1320 MackieControlProtocol::punch_in_press (Button &)
1321 {
1322         bool state = !session->config.get_punch_in();
1323         session->config.set_punch_in (state);
1324         return state;
1325 }
1326
1327 LedState 
1328 MackieControlProtocol::punch_in_release (Button &)
1329 {
1330         return session->config.get_punch_in();
1331 }
1332
1333 LedState 
1334 MackieControlProtocol::punch_out_press (Button &)
1335 {
1336         bool state = !session->config.get_punch_out();
1337         session->config.set_punch_out (state);
1338         return state;
1339 }
1340
1341 LedState 
1342 MackieControlProtocol::punch_out_release (Button &)
1343 {
1344         return session->config.get_punch_out();
1345 }
1346
1347 LedState 
1348 MackieControlProtocol::home_press (Button &)
1349 {
1350         session->goto_start();
1351         return on;
1352 }
1353
1354 LedState 
1355 MackieControlProtocol::home_release (Button &)
1356 {
1357         return off;
1358 }
1359
1360 LedState 
1361 MackieControlProtocol::end_press (Button &)
1362 {
1363         session->goto_end();
1364         return on;
1365 }
1366
1367 LedState 
1368 MackieControlProtocol::end_release (Button &)
1369 {
1370         return off;
1371 }
1372
1373 LedState 
1374 MackieControlProtocol::clicking_press (Button &)
1375 {
1376         bool state = !Config->get_clicking();
1377         Config->set_clicking (state);
1378         return state;
1379 }
1380
1381 LedState 
1382 MackieControlProtocol::clicking_release (Button &)
1383 {
1384         return Config->get_clicking();
1385 }
1386
1387 LedState MackieControlProtocol::global_solo_press (Button &)
1388 {
1389         bool state = !session->soloing();
1390         session->set_solo (session->get_routes(), state);
1391         return state;
1392 }
1393
1394 LedState MackieControlProtocol::global_solo_release (Button &)
1395 {
1396         return session->soloing();
1397 }
1398
1399 ///////////////////////////////////////////
1400 // Session signals
1401 ///////////////////////////////////////////
1402
1403 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
1404 {
1405         if (p == "punch-in")
1406         {
1407                 update_global_button ("punch_in", session->config.get_punch_in());
1408         }
1409         else if (p == "punch-out")
1410         {
1411                 update_global_button ("punch_out", session->config.get_punch_out());
1412         }
1413         else if (p == "clicking")
1414         {
1415                 update_global_button ("clicking", Config->get_clicking());
1416         }
1417         else
1418         {
1419                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
1420         }
1421 }
1422
1423 // RouteList is the set of routes that have just been added
1424 void 
1425 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
1426 {
1427         // currently assigned banks are less than the full set of
1428         // strips, so activate the new strip now.
1429         if (route_signals.size() < route_table.size())
1430         {
1431                 refresh_current_bank();
1432         }
1433         // otherwise route added, but current bank needs no updating
1434
1435         // make sure remote id changes in the new route are handled
1436         typedef ARDOUR::RouteList ARS;
1437
1438         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
1439                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
1440         }
1441 }
1442
1443 void 
1444 MackieControlProtocol::notify_solo_active_changed (bool active)
1445 {
1446         Button * rude_solo = reinterpret_cast<Button*> (surface().controls_by_name["solo"]);
1447         mcu_port().write (builder.build_led (*rude_solo, active ? flashing : off));
1448 }
1449
1450 void 
1451 MackieControlProtocol::notify_remote_id_changed()
1452 {
1453         Sorted sorted = get_sorted_routes();
1454
1455         // if a remote id has been moved off the end, we need to shift
1456         // the current bank backwards.
1457         if (sorted.size() - _current_initial_bank < route_signals.size())
1458         {
1459                 // but don't shift backwards past the zeroth channel
1460                 switch_banks (max((Sorted::size_type) 0, sorted.size() - route_signals.size()));
1461         }
1462         // Otherwise just refresh the current bank
1463         else
1464         {
1465                 refresh_current_bank();
1466         }
1467 }
1468
1469 ///////////////////////////////////////////
1470 // Transport signals
1471 ///////////////////////////////////////////
1472
1473 void 
1474 MackieControlProtocol::notify_record_state_changed()
1475 {
1476         // switch rec button on / off / flashing
1477         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1478         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1479 }
1480
1481 void 
1482 MackieControlProtocol::notify_transport_state_changed()
1483 {
1484         // switch various play and stop buttons on / off
1485         update_global_button ("play", session->transport_rolling());
1486         update_global_button ("stop", !session->transport_rolling());
1487         update_global_button ("loop", session->get_play_loop());
1488
1489         _transport_previously_rolling = session->transport_rolling();
1490
1491         // rec is special because it's tristate
1492         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1493         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1494 }
1495
1496 /////////////////////////////////////
1497 // Bank Switching
1498 /////////////////////////////////////
1499 LedState 
1500 MackieControlProtocol::left_press (Button &)
1501 {
1502         Sorted sorted = get_sorted_routes();
1503         if (sorted.size() > route_table.size())
1504         {
1505                 int new_initial = _current_initial_bank - route_table.size();
1506                 if (new_initial < 0) new_initial = 0;
1507                 if (new_initial != int (_current_initial_bank))
1508                 {
1509                         session->set_dirty();
1510                         switch_banks (new_initial);
1511                 }
1512
1513                 return on;
1514         }
1515         else
1516         {
1517                 return flashing;
1518         }
1519 }
1520
1521 LedState 
1522 MackieControlProtocol::left_release (Button &)
1523 {
1524         return off;
1525 }
1526
1527 LedState 
1528 MackieControlProtocol::right_press (Button &)
1529 {
1530         Sorted sorted = get_sorted_routes();
1531         if (sorted.size() > route_table.size()) {
1532                 uint32_t delta = sorted.size() - (route_table.size() + _current_initial_bank);
1533                 if (delta > route_table.size()) delta = route_table.size();
1534                 if (delta > 0) {
1535                         session->set_dirty();
1536                         switch_banks (_current_initial_bank + delta);
1537                 }
1538
1539                 return on;
1540         } else {
1541                 return flashing;
1542         }
1543 }
1544
1545 LedState 
1546 MackieControlProtocol::right_release (Button &)
1547 {
1548         return off;
1549 }
1550
1551 LedState 
1552 MackieControlProtocol::channel_left_press (Button &)
1553 {
1554         Sorted sorted = get_sorted_routes();
1555         if (sorted.size() > route_table.size())
1556         {
1557                 prev_track();
1558                 return on;
1559         }
1560         else
1561         {
1562                 return flashing;
1563         }
1564 }
1565
1566 LedState 
1567 MackieControlProtocol::channel_left_release (Button &)
1568 {
1569         return off;
1570 }
1571
1572 LedState 
1573 MackieControlProtocol::channel_right_press (Button &)
1574 {
1575         Sorted sorted = get_sorted_routes();
1576         if (sorted.size() > route_table.size())
1577         {
1578                 next_track();
1579                 return on;
1580         }
1581         else
1582         {
1583                 return flashing;
1584         }
1585 }
1586
1587 LedState 
1588 MackieControlProtocol::channel_right_release (Button &)
1589 {
1590         return off;
1591 }
1592
1593 /////////////////////////////////////
1594 // Functions
1595 /////////////////////////////////////
1596 LedState 
1597 MackieControlProtocol::marker_press (Button &)
1598 {
1599         // cut'n'paste from LocationUI::add_new_location()
1600         string markername;
1601         nframes_t where = session->audible_frame();
1602         session->locations()->next_available_name(markername,"mcu");
1603         Location *location = new Location (*session, where, where, markername, Location::IsMark);
1604         session->begin_reversible_command (_("add marker"));
1605         XMLNode &before = session->locations()->get_state();
1606         session->locations()->add (location, true);
1607         XMLNode &after = session->locations()->get_state();
1608         session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
1609         session->commit_reversible_command ();
1610         return on;
1611 }
1612
1613 LedState 
1614 MackieControlProtocol::marker_release (Button &)
1615 {
1616         return off;
1617 }
1618
1619 void 
1620 jog_wheel_state_display (JogWheel::State state, SurfacePort & port)
1621 {
1622         switch (state)
1623         {
1624                 case JogWheel::zoom: port.write (builder.two_char_display ("Zm")); break;
1625                 case JogWheel::scroll: port.write (builder.two_char_display ("Sc")); break;
1626                 case JogWheel::scrub: port.write (builder.two_char_display ("Sb")); break;
1627                 case JogWheel::shuttle: port.write (builder.two_char_display ("Sh")); break;
1628                 case JogWheel::speed: port.write (builder.two_char_display ("Sp")); break;
1629                 case JogWheel::select: port.write (builder.two_char_display ("Se")); break;
1630         }
1631 }
1632
1633 Mackie::LedState 
1634 MackieControlProtocol::zoom_press (Mackie::Button &)
1635 {
1636         _jog_wheel.zoom_state_toggle();
1637         update_global_button ("scrub", _jog_wheel.jog_wheel_state() == JogWheel::scrub);
1638         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1639         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1640 }
1641
1642 Mackie::LedState 
1643 MackieControlProtocol::zoom_release (Mackie::Button &)
1644 {
1645         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1646 }
1647
1648 Mackie::LedState 
1649 MackieControlProtocol::scrub_press (Mackie::Button &)
1650 {
1651         _jog_wheel.scrub_state_cycle();
1652         update_global_button ("zoom", _jog_wheel.jog_wheel_state() == JogWheel::zoom);
1653         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1654         return
1655                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1656                 ||
1657                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1658         ;
1659 }
1660
1661 Mackie::LedState 
1662 MackieControlProtocol::scrub_release (Mackie::Button &)
1663 {
1664         return
1665                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1666                 ||
1667                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1668         ;
1669 }
1670
1671 LedState 
1672 MackieControlProtocol::drop_press (Button &)
1673 {
1674         session->remove_last_capture();
1675         return on;
1676 }
1677
1678 LedState 
1679 MackieControlProtocol::drop_release (Button &)
1680 {
1681         return off;
1682 }
1683
1684 LedState 
1685 MackieControlProtocol::save_press (Button &)
1686 {
1687         session->save_state ("");
1688         return on;
1689 }
1690
1691 LedState 
1692 MackieControlProtocol::save_release (Button &)
1693 {
1694         return off;
1695 }
1696
1697 LedState 
1698 MackieControlProtocol::timecode_beats_press (Button &)
1699 {
1700         switch (_timecode_type)
1701         {
1702                 case ARDOUR::AnyTime::BBT:
1703                         _timecode_type = ARDOUR::AnyTime::Timecode;
1704                         break;
1705                 case ARDOUR::AnyTime::Timecode:
1706                         _timecode_type = ARDOUR::AnyTime::BBT;
1707                         break;
1708                 default:
1709                         ostringstream os;
1710                         os << "Unknown Anytime::Type " << _timecode_type;
1711                         throw runtime_error (os.str());
1712         }
1713         update_timecode_beats_led();
1714         return on;
1715 }
1716
1717 LedState 
1718 MackieControlProtocol::timecode_beats_release (Button &)
1719 {
1720         return off;
1721 }
1722
1723 list<boost::shared_ptr<ARDOUR::Bundle> >
1724 MackieControlProtocol::bundles ()
1725 {
1726         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1727         b.push_back (_input_bundle);
1728         b.push_back (_output_bundle);
1729         return b;
1730 }