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