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