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