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