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