Use a timeout to reset faders' in_use flags when in BCF mode (ie with faders that...
[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/panner_shell.h"
49 #include "ardour/route.h"
50 #include "ardour/session.h"
51 #include "ardour/tempo.h"
52 #include "ardour/types.h"
53 #include "ardour/audioengine.h"
54
55 #include "mackie_control_protocol.h"
56
57 #include "midi_byte_array.h"
58 #include "mackie_control_exception.h"
59 #include "route_signal.h"
60 #include "mackie_midi_builder.h"
61 #include "surface_port.h"
62 #include "surface.h"
63 #include "bcf_surface.h"
64 #include "mackie_surface.h"
65
66 using namespace ARDOUR;
67 using namespace std;
68 using namespace Mackie;
69 using namespace PBD;
70
71 #include "i18n.h"
72
73 MackieMidiBuilder builder;
74
75 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
76 #define ui_bind(f, ...) boost::protect (boost::bind (f, __VA_ARGS__))
77
78 MackieControlProtocol::MackieControlProtocol (Session& session)
79         : ControlProtocol (session, X_("Mackie"), MidiControlUI::instance())
80         , _current_initial_bank (0)
81         , _surface (0)
82         , _jog_wheel (*this)
83         , _timecode_type (ARDOUR::AnyTime::BBT)
84         , _input_bundle (new ARDOUR::Bundle (_("Mackie Control In"), true))
85         , _output_bundle (new ARDOUR::Bundle (_("Mackie Control Out"), false))
86         , _gui (0)
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 boost::shared_ptr<Route> & a, const boost::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 (SurfacePort & port, 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().set_in_use (state);
437
438                 if (ARDOUR::Config->get_mackie_emulation() == "bcf" && state) {
439                         /* BCF faders don't support touch, so add a timeout to reset
440                            their `in_use' state.
441                         */
442                         port.add_in_use_timeout (control.strip().gain(), &control.strip().fader_touch());
443                 }
444         }
445
446         return state;
447 }
448
449 void 
450 MackieControlProtocol::update_led (Mackie::Button & button, Mackie::LedState ls)
451 {
452         if (ls != none)
453         {
454                 SurfacePort * port = 0;
455                 if (button.group().is_strip())
456                 {
457                         if (button.group().is_master())
458                         {
459                                 port = &mcu_port();
460                         }
461                         else
462                         {
463                                 port = &port_for_id (dynamic_cast<const Strip&> (button.group()).index());
464                         }
465                 }
466                 else
467                 {
468                         port = &mcu_port();
469                 }
470                 port->write (builder.build_led (button, ls));
471         }
472 }
473
474 void 
475 MackieControlProtocol::update_timecode_beats_led()
476 {
477         switch (_timecode_type)
478         {
479                 case ARDOUR::AnyTime::BBT:
480                         update_global_led ("beats", on);
481                         update_global_led ("timecode", off);
482                         break;
483                 case ARDOUR::AnyTime::Timecode:
484                         update_global_led ("timecode", on);
485                         update_global_led ("beats", off);
486                         break;
487                 default:
488                         ostringstream os;
489                         os << "Unknown Anytime::Type " << _timecode_type;
490                         throw runtime_error (os.str());
491         }
492 }
493
494 void 
495 MackieControlProtocol::update_global_button (const string & name, LedState ls)
496 {
497         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
498         {
499                 Button * button = dynamic_cast<Button*> (surface().controls_by_name[name]);
500                 mcu_port().write (builder.build_led (button->led(), ls));
501         }
502         else
503         {
504                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", name));
505         }
506 }
507
508 void 
509 MackieControlProtocol::update_global_led (const string & name, LedState ls)
510 {
511         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
512         {
513                 Led * led = dynamic_cast<Led*> (surface().controls_by_name[name]);
514                 mcu_port().write (builder.build_led (*led, ls));
515         }
516         else
517         {
518                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", name));
519         }
520 }
521
522 // send messages to surface to set controls to correct values
523 void 
524 MackieControlProtocol::update_surface()
525 {
526         if (_active)
527         {
528                 // do the initial bank switch to connect signals
529                 // _current_initial_bank is initialised by set_state
530                 switch_banks (_current_initial_bank);
531
532                 // create a RouteSignal for the master route
533
534  boost::shared_ptr<Route> mr = master_route ();
535  if (mr) {
536  master_route_signal = boost::shared_ptr<RouteSignal> (new RouteSignal (mr, *this, master_strip(), mcu_port()));
537  // update strip from route
538  master_route_signal->notify_all();
539  }
540
541                 // sometimes the jog wheel is a pot
542                 surface().blank_jog_ring (mcu_port(), builder);
543
544                 // update global buttons and displays
545                 notify_record_state_changed();
546                 notify_transport_state_changed();
547                 update_timecode_beats_led();
548         }
549 }
550
551 void 
552 MackieControlProtocol::connect_session_signals()
553 {
554         // receive routes added
555         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_route_added, this, _1), midi_ui_context());
556         // receive record state toggled
557         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_record_state_changed, this), midi_ui_context());
558         // receive transport state changed
559         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_transport_state_changed, this), midi_ui_context());
560         // receive punch-in and punch-out
561         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
562         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
563         // receive rude solo changed
564         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), midi_ui_context());
565
566         // make sure remote id changed signals reach here
567         // see also notify_route_added
568         Sorted sorted = get_sorted_routes();
569
570         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
571                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind(&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
572         }
573 }
574
575 void 
576 MackieControlProtocol::add_port (MIDI::Port & midi_input_port, MIDI::Port & midi_output_port, int number)
577 {
578         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("add port %1 %2\n", midi_input_port.name(), midi_output_port.name()));
579
580         MackiePort * sport = new MackiePort (*this, midi_input_port, midi_output_port, number);
581         _ports.push_back (sport);
582         
583         sport->init_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_init, this, sport));
584         sport->active_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_active, this, sport));
585         sport->inactive_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_inactive, this, sport));
586
587         _input_bundle->add_channel (
588                 midi_input_port.name(),
589                 ARDOUR::DataType::MIDI,
590                 session->engine().make_port_name_non_relative (midi_input_port.name())
591                 );
592         
593         _output_bundle->add_channel (
594                 midi_output_port.name(),
595                 ARDOUR::DataType::MIDI,
596                 session->engine().make_port_name_non_relative (midi_output_port.name())
597                 );
598 }
599
600 void 
601 MackieControlProtocol::create_ports()
602 {
603         MIDI::Manager * mm = MIDI::Manager::instance();
604         MIDI::Port * midi_input_port = mm->add_port (
605                 new MIDI::Port (string_compose (_("%1 in"), default_port_name), MIDI::Port::IsInput, session->engine().jack())
606                 );
607         MIDI::Port * midi_output_port = mm->add_port (
608                 new MIDI::Port (string_compose (_("%1 out"), default_port_name), MIDI::Port::IsOutput, session->engine().jack())
609                 );
610
611         // open main port               
612
613         if (!midi_input_port->ok() || !midi_output_port->ok()) {
614                 ostringstream os;
615                 os << _("Mackie control MIDI ports could not be created; Mackie control disabled");
616                 error << os.str() << endmsg;
617                 throw MackieControlException (os.str());
618         }
619
620         add_port (*midi_input_port, *midi_output_port, 0);
621
622         // open extender ports. Up to 9. Should be enough.
623         // could also use mm->get_midi_ports()
624
625         for (int index = 1; index <= 9; ++index) {
626                 MIDI::Port * midi_input_port = mm->add_port (
627                         new MIDI::Port (string_compose (_("mcu_xt_%1 in"), index), MIDI::Port::IsInput, session->engine().jack())
628                         );
629                 MIDI::Port * midi_output_port = mm->add_port (
630                         new MIDI::Port (string_compose (_("mcu_xt_%1 out"), index), MIDI::Port::IsOutput, session->engine().jack())
631                         );
632                 if (midi_input_port->ok() && midi_output_port->ok()) {
633                         add_port (*midi_input_port, *midi_output_port, index);
634                 }
635         }
636 }
637
638 boost::shared_ptr<Route> 
639 MackieControlProtocol::master_route()
640 {
641         return session->master_out ();
642 }
643
644 Strip& 
645 MackieControlProtocol::master_strip()
646 {
647         return dynamic_cast<Strip&> (*surface().groups["master"]);
648 }
649
650 void 
651 MackieControlProtocol::initialize_surface()
652 {
653         // set up the route table
654         int strips = 0;
655         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
656                 strips += (*it)->strips();
657         }
658
659         set_route_table_size (strips);
660
661         // TODO same as code in mackie_port.cc
662         string emulation = ARDOUR::Config->get_mackie_emulation();
663         if (emulation == "bcf")
664         {
665                 _surface = new BcfSurface (strips);
666         }
667         else if (emulation == "mcu")
668         {
669                 _surface = new MackieSurface (strips);
670         }
671         else
672         {
673                 ostringstream os;
674                 os << "no Surface class found for emulation: " << emulation;
675                 throw MackieControlException (os.str());
676         }
677
678         _surface->init();
679
680         // Connect events. Must be after route table otherwise there will be trouble
681
682         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
683                 (*it)->control_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_control_event, this, _1, _2, _3));
684         }
685 }
686
687 void 
688 MackieControlProtocol::close()
689 {
690
691         // must be before other shutdown otherwise polling loop
692         // calls methods on objects that are deleted
693
694         port_connections.drop_connections ();
695         session_connections.drop_connections ();
696         route_connections.drop_connections ();
697
698         if (_surface != 0) {
699                 // These will fail if the port has gone away.
700                 // So catch the exception and do the rest of the
701                 // close afterwards
702                 // because the bcf doesn't respond to the next 3 sysex messages
703                 try {
704                         zero_all();
705                 }
706
707                 catch (exception & e) {
708                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
709                 }
710
711                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
712                         try {
713                                 MackiePort & port = **it;
714                                 // faders to minimum
715                                 port.write_sysex (0x61);
716                                 // All LEDs off
717                                 port.write_sysex (0x62);
718                                 // Reset (reboot into offline mode)
719                                 port.write_sysex (0x63);
720                         }
721                         catch (exception & e) {
722                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
723                         }
724                 }
725
726                 // disconnect routes from strips
727                 clear_route_signals();
728                 delete _surface;
729                 _surface = 0;
730         }
731
732         // shut down MackiePorts
733         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
734                 delete *it;
735         }
736
737         _ports.clear();
738 }
739
740 XMLNode& 
741 MackieControlProtocol::get_state()
742 {
743         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state\n");
744
745         // add name of protocol
746         XMLNode* node = new XMLNode (X_("Protocol"));
747         node->add_property (X_("name"), _name);
748
749         // add current bank
750         ostringstream os;
751         os << _current_initial_bank;
752         node->add_property (X_("bank"), os.str());
753
754         return *node;
755 }
756
757 int 
758 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
759 {
760         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
761
762         int retval = 0;
763
764         // fetch current bank
765
766         if (node.property (X_("bank")) != 0) {
767                 string bank = node.property (X_("bank"))->value();
768                 try {
769                         set_active (true);
770                         uint32_t new_bank = atoi (bank.c_str());
771                         if (_current_initial_bank != new_bank) {
772                                 switch_banks (new_bank);
773                         }
774                 }
775                 catch (exception & e) {
776                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("exception in MackieControlProtocol::set_state: %1\n", e.what()));
777                         return -1;
778                 }
779         }
780
781         return retval;
782 }
783
784 void 
785 MackieControlProtocol::handle_control_event (SurfacePort & port, Control & control, const ControlState & state)
786 {
787         // find the route for the control, if there is one
788         boost::shared_ptr<Route> route;
789         if (control.group().is_strip()) {
790                 if (control.group().is_master()) {
791                         route = master_route();
792                 } else {
793                         uint32_t index = control.ordinal() - 1 + (port.number() * port.strips());
794                         if (index < route_table.size())
795                                 route = route_table[index];
796                         else
797                                 cerr << "Warning: index is " << index << " which is not in the route table, size: " << route_table.size() << endl;
798                 }
799         }
800
801         // This handles control element events from the surface
802         // the state of the controls on the surface is usually updated
803         // from UI events.
804         switch (control.type()) {
805                 case Control::type_fader:
806                         // find the route in the route table for the id
807                         // if the route isn't available, skip it
808                         // at which point the fader should just reset itself
809                         if (route != 0)
810                         {
811                                 route->gain_control()->set_value (state.pos);
812
813                                 if (ARDOUR::Config->get_mackie_emulation() == "bcf") {
814                                         /* reset the timeout while we're still moving the fader */
815                                         port.add_in_use_timeout (control, control.in_use_touch_control);
816                                 }
817
818                                 // must echo bytes back to slider now, because
819                                 // the notifier only works if the fader is not being
820                                 // touched. Which it is if we're getting input.
821                                 port.write (builder.build_fader ((Fader&)control, state.pos));
822                         }
823                         break;
824
825                 case Control::type_button:
826                         if (control.group().is_strip()) {
827                                 // strips
828                                 if (route != 0) {
829                                         handle_strip_button (port, control, state.button_state, route);
830                                 } else {
831                                         // no route so always switch the light off
832                                         // because no signals will be emitted by a non-route
833                                         port.write (builder.build_led (control.led(), off));
834                                 }
835                         } else if (control.group().is_master()) {
836                                 // master fader touch
837                                 if (route != 0) {
838                                         handle_strip_button (port, control, state.button_state, route);
839                                 }
840                         } else {
841                                 // handle all non-strip buttons
842                                 surface().handle_button (*this, state.button_state, dynamic_cast<Button&> (control));
843                         }
844                         break;
845
846                 // pot (jog wheel, external control)
847                 case Control::type_pot:
848                         if (control.group().is_strip()) {
849                                 if (route) {
850                                         boost::shared_ptr<Panner> panner = route->panner_shell()->panner();
851                                         // pan for mono input routes, or stereo linked panners
852                                         if (panner) {
853                                                 double p = panner->position ();
854                                                 
855                                                 // calculate new value, and adjust
856                                                 p += state.delta * state.sign;
857                                                 p = min (1.0, p);
858                                                 p = max (0.0, p);
859                                                 panner->set_position (p);
860                                         }
861                                 }
862                                 else
863                                 {
864                                         // it's a pot for an umnapped route, so turn all the lights off
865                                         port.write (builder.build_led_ring (dynamic_cast<Pot &> (control), off));
866                                 }
867                         }
868                         else
869                         {
870                                 if (control.is_jog())
871                                 {
872                                         _jog_wheel.jog_event (port, control, state);
873                                 }
874                                 else
875                                 {
876                                         cout << "external controller" << state.ticks * state.sign << endl;
877                                 }
878                         }
879                         break;
880
881                 default:
882                         cout << "Control::type not handled: " << control.type() << endl;
883         }
884 }
885
886 /////////////////////////////////////////////////
887 // handlers for Route signals
888 // TODO should these be part of RouteSignal?
889 // They started off as signal/slot handlers for signals
890 // from Route, but they're also used in polling for automation
891 /////////////////////////////////////////////////
892
893 void 
894 MackieControlProtocol::notify_solo_changed (RouteSignal * route_signal)
895 {
896         try
897         {
898                 Button & button = route_signal->strip().solo();
899                 route_signal->port().write (builder.build_led (button, route_signal->route()->soloed()));
900         }
901         catch (exception & e)
902         {
903                 cout << e.what() << endl;
904         }
905 }
906
907 void 
908 MackieControlProtocol::notify_mute_changed (RouteSignal * route_signal)
909 {
910         try
911         {
912                 Button & button = route_signal->strip().mute();
913                 route_signal->port().write (builder.build_led (button, route_signal->route()->muted()));
914         }
915         catch (exception & e)
916         {
917                 cout << e.what() << endl;
918         }
919 }
920
921 void 
922 MackieControlProtocol::notify_record_enable_changed (RouteSignal * route_signal)
923 {
924         try
925         {
926                 Button & button = route_signal->strip().recenable();
927                 route_signal->port().write (builder.build_led (button, route_signal->route()->record_enabled()));
928         }
929         catch (exception & e)
930         {
931                 cout << e.what() << endl;
932         }
933 }
934
935 void MackieControlProtocol::notify_active_changed (RouteSignal *)
936 {
937         try
938         {
939                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::notify_active_changed\n");
940                 refresh_current_bank();
941         }
942         catch (exception & e)
943         {
944                 cout << e.what() << endl;
945         }
946 }
947
948 void 
949 MackieControlProtocol::notify_gain_changed (RouteSignal * route_signal, bool force_update)
950 {
951         try
952         {
953                 Fader & fader = route_signal->strip().gain();
954                 if (!fader.in_use())
955                 {
956                         float gain_value = route_signal->route()->gain_control()->get_value();
957                         // check that something has actually changed
958                         if (force_update || gain_value != route_signal->last_gain_written())
959                         {
960                                 route_signal->port().write (builder.build_fader (fader, gain_value));
961                                 route_signal->last_gain_written (gain_value);
962                         }
963                 }
964         }
965         catch (exception & e)
966         {
967                 cout << e.what() << endl;
968         }
969 }
970
971 void 
972 MackieControlProtocol::notify_property_changed (const PropertyChange& what_changed, RouteSignal * route_signal)
973 {
974         if (!what_changed.contains (Properties::name)) {
975                 return;
976         }
977
978         try
979         {
980                 Strip & strip = route_signal->strip();
981                 
982                 /* XXX: not sure about this check to only display stuff for strips of index < 8 */
983                 if (!strip.is_master() && strip.index() < 8)
984                 {
985                         string line1;
986                         string fullname = route_signal->route()->name();
987
988                         if (fullname.length() <= 6)
989                         {
990                                 line1 = fullname;
991                         }
992                         else
993                         {
994                                 line1 = PBD::short_version (fullname, 6);
995                         }
996
997                         SurfacePort & port = route_signal->port();
998                         port.write (builder.strip_display (port, strip, 0, line1));
999                         port.write (builder.strip_display_blank (port, strip, 1));
1000                 }
1001         }
1002         catch (exception & e)
1003         {
1004                 cout << e.what() << endl;
1005         }
1006 }
1007
1008 void 
1009 MackieControlProtocol::notify_panner_changed (RouteSignal * route_signal, bool force_update)
1010 {
1011         try
1012         {
1013                 Pot & pot = route_signal->strip().vpot();
1014                 boost::shared_ptr<Panner> panner = route_signal->route()->panner();
1015                 if (panner) {
1016                         double pos = panner->position ();
1017
1018                         // cache the MidiByteArray here, because the mackie led control is much lower
1019                         // resolution than the panner control. So we save lots of byte
1020                         // sends in spite of more work on the comparison
1021                         MidiByteArray bytes = builder.build_led_ring (pot, ControlState (on, pos), MackieMidiBuilder::midi_pot_mode_dot);
1022                         // check that something has actually changed
1023                         if (force_update || bytes != route_signal->last_pan_written())
1024                         {
1025                                 route_signal->port().write (bytes);
1026                                 route_signal->last_pan_written (bytes);
1027                         }
1028                 }
1029                 else
1030                 {
1031                         route_signal->port().write (builder.zero_control (pot));
1032                 }
1033         }
1034         catch (exception & e)
1035         {
1036                 cout << e.what() << endl;
1037         }
1038 }
1039
1040 // TODO handle plugin automation polling
1041 void 
1042 MackieControlProtocol::update_automation (RouteSignal & rs)
1043 {
1044         ARDOUR::AutoState gain_state = rs.route()->gain_control()->automation_state();
1045
1046         if (gain_state == Touch || gain_state == Play)
1047         {
1048                 notify_gain_changed (&rs, false);
1049         }
1050
1051         if (rs.route()->panner()) {
1052                 ARDOUR::AutoState panner_state = rs.route()->panner()->automation_state();
1053                 if (panner_state == Touch || panner_state == Play)
1054                 {
1055                         notify_panner_changed (&rs, false);
1056                 }
1057         }
1058 }
1059
1060 string 
1061 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
1062 {
1063         Timecode::BBT_Time bbt_time;
1064         session->bbt_time (now_frame, bbt_time);
1065
1066         // According to the Logic docs
1067         // digits: 888/88/88/888
1068         // BBT mode: Bars/Beats/Subdivisions/Ticks
1069         ostringstream os;
1070         os << setw(3) << setfill('0') << bbt_time.bars;
1071         os << setw(2) << setfill('0') << bbt_time.beats;
1072
1073         // figure out subdivisions per beat
1074         const Meter & meter = session->tempo_map().meter_at (now_frame);
1075         int subdiv = 2;
1076         if (meter.note_divisor() == 8 && (meter.beats_per_bar() == 12.0 || meter.beats_per_bar() == 9.0 || meter.beats_per_bar() == 6.0))
1077         {
1078                 subdiv = 3;
1079         }
1080
1081         uint32_t subdivisions = bbt_time.ticks / uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
1082         uint32_t ticks = bbt_time.ticks % uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
1083
1084         os << setw(2) << setfill('0') << subdivisions + 1;
1085         os << setw(3) << setfill('0') << ticks;
1086
1087         return os.str();
1088 }
1089
1090 string 
1091 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
1092 {
1093         Timecode::Time timecode;
1094         session->timecode_time (now_frame, timecode);
1095
1096         // According to the Logic docs
1097         // digits: 888/88/88/888
1098         // Timecode mode: Hours/Minutes/Seconds/Frames
1099         ostringstream os;
1100         os << setw(3) << setfill('0') << timecode.hours;
1101         os << setw(2) << setfill('0') << timecode.minutes;
1102         os << setw(2) << setfill('0') << timecode.seconds;
1103         os << setw(3) << setfill('0') << timecode.frames;
1104
1105         return os.str();
1106 }
1107
1108 void 
1109 MackieControlProtocol::update_timecode_display()
1110 {
1111         if (surface().has_timecode_display())
1112         {
1113                 // do assignment here so current_frame is fixed
1114                 framepos_t current_frame = session->transport_frame();
1115                 string timecode;
1116
1117                 switch (_timecode_type)
1118                 {
1119                         case ARDOUR::AnyTime::BBT:
1120                                 timecode = format_bbt_timecode (current_frame);
1121                                 break;
1122                         case ARDOUR::AnyTime::Timecode:
1123                                 timecode = format_timecode_timecode (current_frame);
1124                                 break;
1125                         default:
1126                                 ostringstream os;
1127                                 os << "Unknown timecode: " << _timecode_type;
1128                                 throw runtime_error (os.str());
1129                 }
1130
1131                 // only write the timecode string to the MCU if it's changed
1132                 // since last time. This is to reduce midi bandwidth used.
1133                 if (timecode != _timecode_last)
1134                 {
1135                         surface().display_timecode (mcu_port(), builder, timecode, _timecode_last);
1136                         _timecode_last = timecode;
1137                 }
1138         }
1139 }
1140
1141 void 
1142 MackieControlProtocol::poll_session_data()
1143 {
1144         // XXX need to attach this to a timer in the MIDI UI event loop (20msec)
1145
1146         if (_active) {
1147                 // do all currently mapped routes
1148                 for (RouteSignals::iterator it = route_signals.begin(); it != route_signals.end(); ++it) {
1149                         update_automation (**it);
1150                 }
1151
1152                 // and the master strip
1153                 if (master_route_signal != 0) {
1154                         update_automation (*master_route_signal);
1155                 }
1156
1157                 update_timecode_display();
1158         }
1159 }
1160
1161 /////////////////////////////////////
1162 // Transport Buttons
1163 /////////////////////////////////////
1164
1165 LedState 
1166 MackieControlProtocol::frm_left_press (Button &)
1167 {
1168         // can use first_mark_before/after as well
1169         unsigned long elapsed = _frm_left_last.restart();
1170
1171         Location * loc = session->locations()->first_location_before (
1172                 session->transport_frame()
1173         );
1174
1175         // allow a quick double to go past a previous mark
1176         if (session->transport_rolling() && elapsed < 500 && loc != 0)
1177         {
1178                 Location * loc_two_back = session->locations()->first_location_before (loc->start());
1179                 if (loc_two_back != 0)
1180                 {
1181                         loc = loc_two_back;
1182                 }
1183         }
1184
1185         // move to the location, if it's valid
1186         if (loc != 0)
1187         {
1188                 session->request_locate (loc->start(), session->transport_rolling());
1189         }
1190
1191         return on;
1192 }
1193
1194 LedState 
1195 MackieControlProtocol::frm_left_release (Button &)
1196 {
1197         return off;
1198 }
1199
1200 LedState 
1201 MackieControlProtocol::frm_right_press (Button &)
1202 {
1203         // can use first_mark_before/after as well
1204         Location * loc = session->locations()->first_location_after (
1205                 session->transport_frame()
1206         );
1207         if (loc != 0) session->request_locate (loc->start(), session->transport_rolling());
1208         return on;
1209 }
1210
1211 LedState 
1212 MackieControlProtocol::frm_right_release (Button &)
1213 {
1214         return off;
1215 }
1216
1217 LedState 
1218 MackieControlProtocol::stop_press (Button &)
1219 {
1220         session->request_stop();
1221         return on;
1222 }
1223
1224 LedState 
1225 MackieControlProtocol::stop_release (Button &)
1226 {
1227         return session->transport_stopped();
1228 }
1229
1230 LedState 
1231 MackieControlProtocol::play_press (Button &)
1232 {
1233         session->request_transport_speed (1.0);
1234         return on;
1235 }
1236
1237 LedState 
1238 MackieControlProtocol::play_release (Button &)
1239 {
1240         return session->transport_rolling();
1241 }
1242
1243 LedState 
1244 MackieControlProtocol::record_press (Button &)
1245 {
1246         if (session->get_record_enabled()) {
1247                 session->disable_record (false);
1248         } else {
1249                 session->maybe_enable_record();
1250         }
1251         return on;
1252 }
1253
1254 LedState 
1255 MackieControlProtocol::record_release (Button &)
1256 {
1257         if (session->get_record_enabled()) {
1258                 if (session->transport_rolling()) {
1259                         return on;
1260                 } else {
1261                         return flashing;
1262                 }
1263         } else {
1264                 return off;
1265         }
1266 }
1267
1268 LedState 
1269 MackieControlProtocol::rewind_press (Button &)
1270 {
1271         _jog_wheel.push (JogWheel::speed);
1272         _jog_wheel.transport_direction (-1);
1273         session->request_transport_speed (-_jog_wheel.transport_speed());
1274         return on;
1275 }
1276
1277 LedState 
1278 MackieControlProtocol::rewind_release (Button &)
1279 {
1280         _jog_wheel.pop();
1281         _jog_wheel.transport_direction (0);
1282         if (_transport_previously_rolling)
1283                 session->request_transport_speed (1.0);
1284         else
1285                 session->request_stop();
1286         return off;
1287 }
1288
1289 LedState 
1290 MackieControlProtocol::ffwd_press (Button &)
1291 {
1292         _jog_wheel.push (JogWheel::speed);
1293         _jog_wheel.transport_direction (1);
1294         session->request_transport_speed (_jog_wheel.transport_speed());
1295         return on;
1296 }
1297
1298 LedState 
1299 MackieControlProtocol::ffwd_release (Button &)
1300 {
1301         _jog_wheel.pop();
1302         _jog_wheel.transport_direction (0);
1303         if (_transport_previously_rolling)
1304                 session->request_transport_speed (1.0);
1305         else
1306                 session->request_stop();
1307         return off;
1308 }
1309
1310 LedState 
1311 MackieControlProtocol::loop_press (Button &)
1312 {
1313         session->request_play_loop (!session->get_play_loop());
1314         return on;
1315 }
1316
1317 LedState 
1318 MackieControlProtocol::loop_release (Button &)
1319 {
1320         return session->get_play_loop();
1321 }
1322
1323 LedState 
1324 MackieControlProtocol::punch_in_press (Button &)
1325 {
1326         bool state = !session->config.get_punch_in();
1327         session->config.set_punch_in (state);
1328         return state;
1329 }
1330
1331 LedState 
1332 MackieControlProtocol::punch_in_release (Button &)
1333 {
1334         return session->config.get_punch_in();
1335 }
1336
1337 LedState 
1338 MackieControlProtocol::punch_out_press (Button &)
1339 {
1340         bool state = !session->config.get_punch_out();
1341         session->config.set_punch_out (state);
1342         return state;
1343 }
1344
1345 LedState 
1346 MackieControlProtocol::punch_out_release (Button &)
1347 {
1348         return session->config.get_punch_out();
1349 }
1350
1351 LedState 
1352 MackieControlProtocol::home_press (Button &)
1353 {
1354         session->goto_start();
1355         return on;
1356 }
1357
1358 LedState 
1359 MackieControlProtocol::home_release (Button &)
1360 {
1361         return off;
1362 }
1363
1364 LedState 
1365 MackieControlProtocol::end_press (Button &)
1366 {
1367         session->goto_end();
1368         return on;
1369 }
1370
1371 LedState 
1372 MackieControlProtocol::end_release (Button &)
1373 {
1374         return off;
1375 }
1376
1377 LedState 
1378 MackieControlProtocol::clicking_press (Button &)
1379 {
1380         bool state = !Config->get_clicking();
1381         Config->set_clicking (state);
1382         return state;
1383 }
1384
1385 LedState 
1386 MackieControlProtocol::clicking_release (Button &)
1387 {
1388         return Config->get_clicking();
1389 }
1390
1391 LedState MackieControlProtocol::global_solo_press (Button &)
1392 {
1393         bool state = !session->soloing();
1394         session->set_solo (session->get_routes(), state);
1395         return state;
1396 }
1397
1398 LedState MackieControlProtocol::global_solo_release (Button &)
1399 {
1400         return session->soloing();
1401 }
1402
1403 ///////////////////////////////////////////
1404 // Session signals
1405 ///////////////////////////////////////////
1406
1407 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
1408 {
1409         if (p == "punch-in")
1410         {
1411                 update_global_button ("punch_in", session->config.get_punch_in());
1412         }
1413         else if (p == "punch-out")
1414         {
1415                 update_global_button ("punch_out", session->config.get_punch_out());
1416         }
1417         else if (p == "clicking")
1418         {
1419                 update_global_button ("clicking", Config->get_clicking());
1420         }
1421         else
1422         {
1423                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
1424         }
1425 }
1426
1427 // RouteList is the set of routes that have just been added
1428 void 
1429 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
1430 {
1431         // currently assigned banks are less than the full set of
1432         // strips, so activate the new strip now.
1433         if (route_signals.size() < route_table.size())
1434         {
1435                 refresh_current_bank();
1436         }
1437         // otherwise route added, but current bank needs no updating
1438
1439         // make sure remote id changes in the new route are handled
1440         typedef ARDOUR::RouteList ARS;
1441
1442         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
1443                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
1444         }
1445 }
1446
1447 void 
1448 MackieControlProtocol::notify_solo_active_changed (bool active)
1449 {
1450         Button * rude_solo = reinterpret_cast<Button*> (surface().controls_by_name["solo"]);
1451         mcu_port().write (builder.build_led (*rude_solo, active ? flashing : off));
1452 }
1453
1454 void 
1455 MackieControlProtocol::notify_remote_id_changed()
1456 {
1457         Sorted sorted = get_sorted_routes();
1458
1459         // if a remote id has been moved off the end, we need to shift
1460         // the current bank backwards.
1461         if (sorted.size() - _current_initial_bank < route_signals.size())
1462         {
1463                 // but don't shift backwards past the zeroth channel
1464                 switch_banks (max((Sorted::size_type) 0, sorted.size() - route_signals.size()));
1465         }
1466         // Otherwise just refresh the current bank
1467         else
1468         {
1469                 refresh_current_bank();
1470         }
1471 }
1472
1473 ///////////////////////////////////////////
1474 // Transport signals
1475 ///////////////////////////////////////////
1476
1477 void 
1478 MackieControlProtocol::notify_record_state_changed()
1479 {
1480         // switch rec button on / off / flashing
1481         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1482         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1483 }
1484
1485 void 
1486 MackieControlProtocol::notify_transport_state_changed()
1487 {
1488         // switch various play and stop buttons on / off
1489         update_global_button ("play", session->transport_rolling());
1490         update_global_button ("stop", !session->transport_rolling());
1491         update_global_button ("loop", session->get_play_loop());
1492
1493         _transport_previously_rolling = session->transport_rolling();
1494
1495         // rec is special because it's tristate
1496         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1497         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1498 }
1499
1500 /////////////////////////////////////
1501 // Bank Switching
1502 /////////////////////////////////////
1503 LedState 
1504 MackieControlProtocol::left_press (Button &)
1505 {
1506         Sorted sorted = get_sorted_routes();
1507         if (sorted.size() > route_table.size())
1508         {
1509                 int new_initial = _current_initial_bank - route_table.size();
1510                 if (new_initial < 0) new_initial = 0;
1511                 if (new_initial != int (_current_initial_bank))
1512                 {
1513                         session->set_dirty();
1514                         switch_banks (new_initial);
1515                 }
1516
1517                 return on;
1518         }
1519         else
1520         {
1521                 return flashing;
1522         }
1523 }
1524
1525 LedState 
1526 MackieControlProtocol::left_release (Button &)
1527 {
1528         return off;
1529 }
1530
1531 LedState 
1532 MackieControlProtocol::right_press (Button &)
1533 {
1534         Sorted sorted = get_sorted_routes();
1535         if (sorted.size() > route_table.size()) {
1536                 uint32_t delta = sorted.size() - (route_table.size() + _current_initial_bank);
1537                 if (delta > route_table.size()) delta = route_table.size();
1538                 if (delta > 0) {
1539                         session->set_dirty();
1540                         switch_banks (_current_initial_bank + delta);
1541                 }
1542
1543                 return on;
1544         } else {
1545                 return flashing;
1546         }
1547 }
1548
1549 LedState 
1550 MackieControlProtocol::right_release (Button &)
1551 {
1552         return off;
1553 }
1554
1555 LedState 
1556 MackieControlProtocol::channel_left_press (Button &)
1557 {
1558         Sorted sorted = get_sorted_routes();
1559         if (sorted.size() > route_table.size())
1560         {
1561                 prev_track();
1562                 return on;
1563         }
1564         else
1565         {
1566                 return flashing;
1567         }
1568 }
1569
1570 LedState 
1571 MackieControlProtocol::channel_left_release (Button &)
1572 {
1573         return off;
1574 }
1575
1576 LedState 
1577 MackieControlProtocol::channel_right_press (Button &)
1578 {
1579         Sorted sorted = get_sorted_routes();
1580         if (sorted.size() > route_table.size())
1581         {
1582                 next_track();
1583                 return on;
1584         }
1585         else
1586         {
1587                 return flashing;
1588         }
1589 }
1590
1591 LedState 
1592 MackieControlProtocol::channel_right_release (Button &)
1593 {
1594         return off;
1595 }
1596
1597 /////////////////////////////////////
1598 // Functions
1599 /////////////////////////////////////
1600 LedState 
1601 MackieControlProtocol::marker_press (Button &)
1602 {
1603         // cut'n'paste from LocationUI::add_new_location()
1604         string markername;
1605         framepos_t where = session->audible_frame();
1606         session->locations()->next_available_name(markername,"mcu");
1607         Location *location = new Location (*session, where, where, markername, Location::IsMark);
1608         session->begin_reversible_command (_("add marker"));
1609         XMLNode &before = session->locations()->get_state();
1610         session->locations()->add (location, true);
1611         XMLNode &after = session->locations()->get_state();
1612         session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
1613         session->commit_reversible_command ();
1614         return on;
1615 }
1616
1617 LedState 
1618 MackieControlProtocol::marker_release (Button &)
1619 {
1620         return off;
1621 }
1622
1623 void 
1624 jog_wheel_state_display (JogWheel::State state, SurfacePort & port)
1625 {
1626         switch (state)
1627         {
1628                 case JogWheel::zoom: port.write (builder.two_char_display ("Zm")); break;
1629                 case JogWheel::scroll: port.write (builder.two_char_display ("Sc")); break;
1630                 case JogWheel::scrub: port.write (builder.two_char_display ("Sb")); break;
1631                 case JogWheel::shuttle: port.write (builder.two_char_display ("Sh")); break;
1632                 case JogWheel::speed: port.write (builder.two_char_display ("Sp")); break;
1633                 case JogWheel::select: port.write (builder.two_char_display ("Se")); break;
1634         }
1635 }
1636
1637 Mackie::LedState 
1638 MackieControlProtocol::zoom_press (Mackie::Button &)
1639 {
1640         _jog_wheel.zoom_state_toggle();
1641         update_global_button ("scrub", _jog_wheel.jog_wheel_state() == JogWheel::scrub);
1642         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1643         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1644 }
1645
1646 Mackie::LedState 
1647 MackieControlProtocol::zoom_release (Mackie::Button &)
1648 {
1649         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1650 }
1651
1652 Mackie::LedState 
1653 MackieControlProtocol::scrub_press (Mackie::Button &)
1654 {
1655         _jog_wheel.scrub_state_cycle();
1656         update_global_button ("zoom", _jog_wheel.jog_wheel_state() == JogWheel::zoom);
1657         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1658         return
1659                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1660                 ||
1661                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1662         ;
1663 }
1664
1665 Mackie::LedState 
1666 MackieControlProtocol::scrub_release (Mackie::Button &)
1667 {
1668         return
1669                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1670                 ||
1671                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1672         ;
1673 }
1674
1675 LedState 
1676 MackieControlProtocol::drop_press (Button &)
1677 {
1678         session->remove_last_capture();
1679         return on;
1680 }
1681
1682 LedState 
1683 MackieControlProtocol::drop_release (Button &)
1684 {
1685         return off;
1686 }
1687
1688 LedState 
1689 MackieControlProtocol::save_press (Button &)
1690 {
1691         session->save_state ("");
1692         return on;
1693 }
1694
1695 LedState 
1696 MackieControlProtocol::save_release (Button &)
1697 {
1698         return off;
1699 }
1700
1701 LedState 
1702 MackieControlProtocol::timecode_beats_press (Button &)
1703 {
1704         switch (_timecode_type)
1705         {
1706                 case ARDOUR::AnyTime::BBT:
1707                         _timecode_type = ARDOUR::AnyTime::Timecode;
1708                         break;
1709                 case ARDOUR::AnyTime::Timecode:
1710                         _timecode_type = ARDOUR::AnyTime::BBT;
1711                         break;
1712                 default:
1713                         ostringstream os;
1714                         os << "Unknown Anytime::Type " << _timecode_type;
1715                         throw runtime_error (os.str());
1716         }
1717         update_timecode_beats_led();
1718         return on;
1719 }
1720
1721 LedState 
1722 MackieControlProtocol::timecode_beats_release (Button &)
1723 {
1724         return off;
1725 }
1726
1727 list<boost::shared_ptr<ARDOUR::Bundle> >
1728 MackieControlProtocol::bundles ()
1729 {
1730         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1731         b.push_back (_input_bundle);
1732         b.push_back (_output_bundle);
1733         return b;
1734 }