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