2d443ad711ac72c25cf636b28465cd82373594d8
[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         $Id: mackie_control_protocol.cc 1059 2006-11-02 12:27:49Z paul $
19 */
20
21 #include <iostream>
22 #include <algorithm>
23 #include <cmath>
24 #include <sstream>
25 #include <vector>
26
27 #define __STDC_FORMAT_MACROS
28 #include <inttypes.h>
29 #include <float.h>
30 #include <sys/time.h>
31 #include <errno.h>
32 #include <poll.h>
33
34 #include <boost/shared_array.hpp>
35
36 #include <midi++/types.h>
37 #include <midi++/port.h>
38 #include <midi++/manager.h>
39 #include <pbd/pthread_utils.h>
40 #include <pbd/error.h>
41
42 #include <ardour/route.h>
43 #include <ardour/session.h>
44 #include <ardour/location.h>
45 #include <ardour/dB.h>
46 #include <ardour/panner.h>
47
48 #include "mackie_control_protocol.h"
49
50 #include "midi_byte_array.h"
51 #include "mackie_control_exception.h"
52 #include "route_signal.h"
53 #include "mackie_midi_builder.h"
54 #include "surface_port.h"
55 #include "surface.h"
56 #include "bcf_surface.h"
57 #include "mackie_surface.h"
58
59 using namespace ARDOUR;
60 using namespace std;
61 using namespace sigc;
62 using namespace Mackie;
63 using namespace PBD;
64
65 using boost::shared_ptr;
66
67 #include "i18n.h"
68
69 MackieMidiBuilder builder;
70
71 // Copied from tranzport_control_protocol.cc
72 static inline double 
73 gain_to_slider_position (ARDOUR::gain_t g)
74 {
75         if (g == 0) return 0;
76         return pow((6.0*log(g)/log(2.0)+192.0)/198.0, 8.0);
77 }
78
79 /*
80         Copied from tranzport_control_protocol.cc
81         TODO this seems to return slightly wrong values, namely
82         with the UI slider at max, we get a 0.99something value.
83 */
84 static inline ARDOUR::gain_t 
85 slider_position_to_gain (double pos)
86 {
87         /* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
88         if (pos == 0.0) return 0;
89         return pow (2.0,(sqrt(sqrt(sqrt(pos)))*198.0-192.0)/6.0);
90 }
91
92 MackieControlProtocol::MackieControlProtocol (Session& session)
93         : ControlProtocol  (session, X_("Mackie"))
94         , _current_initial_bank( 0 )
95         , connections_back( _connections )
96         , _surface( 0 )
97         , _ports_changed( false )
98         , pfd( 0 )
99         , nfds( 0 )
100 {
101         cout << "MackieControlProtocol::MackieControlProtocol" << endl;
102         // will start reading from ports, as soon as there are some
103         pthread_create_and_store (X_("mackie monitor"), &thread, 0, _monitor_work, this);
104 }
105
106 MackieControlProtocol::~MackieControlProtocol()
107 {
108         cout << "~MackieControlProtocol::MackieControlProtocol" << endl;
109         close();
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         
206         // sort in remote_id order, and exclude master, control and hidden routes
207         for ( Session::RouteList::iterator it = routes->begin(); it != routes->end(); ++it )
208         {
209                 Route & route = **it;
210                 if ( route.active() && !route.master() && !route.hidden() && !route.control() )
211                 {
212                         sorted.push_back( *it );
213                 }
214         }
215         sort( sorted.begin(), sorted.end(), RouteByRemoteId() );
216         return sorted;
217 }
218
219 void MackieControlProtocol::refresh_current_bank()
220 {
221         switch_banks( _current_initial_bank );
222 }
223
224 void MackieControlProtocol::switch_banks( int initial )
225 {
226         // DON'T prevent bank switch if initial == _current_initial_bank
227         // because then this method can't be used as a refresh
228         
229         // sanity checking
230         Sorted sorted = get_sorted_routes();
231         int delta = sorted.size() - route_table.size();
232         if ( initial < 0 || ( delta > 0 && initial > delta ) )
233         {
234                 cout << "not switching to " << initial << endl;
235                 return;
236         }
237         _current_initial_bank = initial;
238         
239         // first clear the signals from old routes
240         // taken care of by the RouteSignal destructors
241         clear_route_signals();
242         
243         // now set the signals for new routes
244         if ( _current_initial_bank <= sorted.size() )
245         {
246                 // fetch the bank start and end to switch to
247                 uint32_t end_pos = min( route_table.size(), sorted.size() );
248                 Sorted::iterator it = sorted.begin() + _current_initial_bank;
249                 Sorted::iterator end = sorted.begin() + _current_initial_bank + end_pos;
250                 cout << "switch to " << _current_initial_bank << ", " << end_pos << endl;
251                 
252                 // link routes to strips
253                 uint32_t i = 0;
254                 for ( ; it != end && it != sorted.end(); ++it, ++i )
255                 {
256                         boost::shared_ptr<Route> route = *it;
257                         Strip & strip = *surface().strips[i];
258                         cout << "remote id " << route->remote_control_id() << " connecting " << route->name() << " to " << strip.name() << " with port " << port_for_id(i) << endl;
259                         route_table[i] = route;
260                         RouteSignal * rs = new RouteSignal( *route, *this, strip, port_for_id(i) );
261                         route_signals.push_back( rs );
262                         // update strip from route
263                         rs->notify_all();
264                 }
265                 
266                 // create dead strips if there aren't enough routes to
267                 // fill a bank
268                 for ( ; i < route_table.size(); ++i )
269                 {
270                         Strip & strip = *surface().strips[i];
271                         // send zero for this strip
272                         port_for_id(i).write( builder.zero_strip( strip ) );
273                 }
274         }
275         
276         // display the current start bank.
277         if ( mcu_port().emulation() == MackiePort::bcf2000 )
278         {
279                 if ( _current_initial_bank == 0 )
280                 {
281                         // send Ar. to 2-char display on the master
282                         mcu_port().write( builder.two_char_display( "Ar", ".." ) );
283                 }
284                 else
285                 {
286                         // write the current first remote_id to the 2-char display
287                         mcu_port().write( builder.two_char_display( _current_initial_bank ) );
288                 }
289         }
290 }
291
292 void MackieControlProtocol::zero_all()
293 {
294         // TODO turn off 55-char and SMPTE displays
295         
296         if ( mcu_port().emulation() == MackiePort::bcf2000 )
297         {
298                 // clear 2-char display
299                 mcu_port().write( builder.two_char_display( "LC" ) );
300         }
301         
302         // zero all strips
303         for ( Surface::Strips::iterator it = surface().strips.begin(); it != surface().strips.end(); ++it )
304         {
305                 port_for_id( (*it)->index() ).write( builder.zero_strip( **it ) );
306         }
307         
308         // and the master strip
309         mcu_port().write( builder.zero_strip( master_strip() ) );
310         
311         // and the led ring for the master strip, in bcf mode
312         if ( mcu_port().emulation() == MackiePort::bcf2000 )
313         {
314                 Control & control = *surface().controls_by_name["jog"];
315                 mcu_port().write( builder.build_led_ring( dynamic_cast<Pot &>( control ), off ) );
316         }
317         
318         // turn off global buttons and leds
319         // global buttons are only ever on mcu_port, so we don't have
320         // to figure out which port.
321         for ( Surface::Controls::iterator it = surface().controls.begin(); it != surface().controls.end(); ++it )
322         {
323                 Control & control = **it;
324                 if ( !control.group().is_strip() && control.accepts_feedback() )
325                 {
326                         mcu_port().write( builder.zero_control( control ) );
327                 }
328         }
329 }
330
331 int MackieControlProtocol::set_active (bool yn)
332 {
333         if ( yn != _active )
334         {
335                 try
336                 {
337                         // the reason for the locking and unlocking is that
338                         // glibmm can't do a condition wait on a RecMutex
339                         if ( yn )
340                         {
341                                 // TODO what happens if this fails half way?
342                                 cout << "set_active true" << endl;
343                                 
344                                 // create MackiePorts
345                                 {
346                                         Glib::Mutex::Lock lock( update_mutex );
347                                         create_ports();
348                                 }
349                                 
350                                 // wait until poll thread is running, with ports to poll
351                                 // the mutex is only there because conditions require a mutex
352                                 {
353                                         Glib::Mutex::Lock lock( update_mutex );
354                                         while ( nfds == 0 ) update_cond.wait( update_mutex );
355                                 }
356                                 
357                                 // now initialise MackiePorts - ie exchange sysex messages
358                                 for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
359                                 {
360                                         (*it)->open();
361                                 }
362                                 
363                                 // wait until all ports are active
364                                 // TODO a more sophisticate approach would
365                                 // allow things to start up with only an MCU, even if
366                                 // extenders were specified but not responding.
367                                 for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
368                                 {
369                                         (*it)->wait_for_init();
370                                 }
371                                 
372                                 // create surface object. This depends on the ports being
373                                 // correctly initialised
374                                 initialize_surface();
375                                 connect_session_signals();
376                                 
377                                 // yeehah!
378                                 _active = true;
379                                 
380                                 // send current control positions to surface
381                                 // must come after _active = true otherwise it won't run
382                                 update_surface();
383                         }
384                         else
385                         {
386                                 cout << "set_active false" << endl;
387                                 close();
388                                 _active = false;
389                         }
390                 }
391                 catch( exception & e )
392                 {
393                         cout << "set_active to false because " << e.what() << endl;
394                         _active = false;
395                         throw;
396                 }
397         }
398
399         return 0;
400 }
401
402 bool MackieControlProtocol::handle_strip_button( Control & control, ButtonState bs, boost::shared_ptr<Route> route )
403 {
404         bool state = false;
405
406         if ( bs == press )
407         {
408                 if ( control.name() == "recenable" )
409                 {
410                         state = !route->record_enabled();
411                         route->set_record_enable( state, this );
412                 }
413                 else if ( control.name() == "mute" )
414                 {
415                         state = !route->muted();
416                         route->set_mute( state, this );
417                 }
418                 else if ( control.name() == "solo" )
419                 {
420                         state = !route->soloed();
421                         route->set_solo( state, this );
422                 }
423                 else if ( control.name() == "select" )
424                 {
425                         // TODO make the track selected. Whatever that means.
426                         //state = default_button_press( dynamic_cast<Button&>( control ) );
427                 }
428                 else if ( control.name() == "vselect" )
429                 {
430                         // TODO could be used to select different things to apply the pot to?
431                         //state = default_button_press( dynamic_cast<Button&>( control ) );
432                 }
433         }
434         
435         if ( control.name() == "fader_touch" )
436         {
437                 state = bs == press;
438                 control.strip().gain().touch( state );
439         }
440         
441         return state;
442 }
443
444 void MackieControlProtocol::update_led( Mackie::Button & button, Mackie::LedState ls )
445 {
446         MackiePort * port = 0;
447         if ( button.group().is_strip() )
448         {
449                 if ( button.group().is_master() )
450                 {
451                         port = &mcu_port();
452                 }
453                 else
454                 {
455                         port = &port_for_id( dynamic_cast<const Strip&>( button.group() ).index() );
456                 }
457         }
458         else
459         {
460                 port = &mcu_port();
461         }
462         if ( ls != none ) port->write( builder.build_led( button, ls ) );
463 }
464
465 void MackieControlProtocol::update_global_button( const string & name, LedState ls )
466 {
467         if ( surface().controls_by_name.find( name ) !=surface().controls_by_name.end() )
468         {
469                 Button * button = dynamic_cast<Button*>( surface().controls_by_name[name] );
470                 mcu_port().write( builder.build_led( button->led(), ls ) );
471         }
472         else
473         {
474                 cout << "Button " << name << " not found" << endl;
475         }
476 }
477
478 // send messages to surface to set controls to correct values
479 void MackieControlProtocol::update_surface()
480 {
481         if ( _active )
482         {
483                 // do the initial bank switch to connect signals
484                 // _current_initial_bank is initialised by set_state
485                 switch_banks( _current_initial_bank );
486                 
487                 // create a RouteSignal for the master route
488                 // but only the first time around
489                 master_route_signal = shared_ptr<RouteSignal>( new RouteSignal( *master_route(), *this, master_strip(), mcu_port() ) );
490                 // update strip from route
491                 master_route_signal->notify_all();
492                 
493                 // update global buttons and displays
494                 notify_record_state_changed();
495                 notify_transport_state_changed();
496         }
497 }
498
499 void MackieControlProtocol::connect_session_signals()
500 {
501         // receive routes added
502         connections_back = session->RouteAdded.connect( ( mem_fun (*this, &MackieControlProtocol::notify_route_added) ) );
503         // receive record state toggled
504         connections_back = session->RecordStateChanged.connect( ( mem_fun (*this, &MackieControlProtocol::notify_record_state_changed) ) );
505         // receive transport state changed
506         connections_back = session->TransportStateChange.connect( ( mem_fun (*this, &MackieControlProtocol::notify_transport_state_changed) ) );
507         // receive punch-in and punch-out
508         connections_back = Config->ParameterChanged.connect( ( mem_fun (*this, &MackieControlProtocol::notify_parameter_changed) ) );
509         // receive rude solo changed
510         connections_back = session->SoloActive.connect( ( mem_fun (*this, &MackieControlProtocol::notify_solo_active_changed) ) );
511 }
512
513 void MackieControlProtocol::add_port( MIDI::Port & midi_port, int number )
514 {
515         MackiePort * sport = new MackiePort( *this, midi_port, number );
516         _ports.push_back( sport );
517
518         connections_back = sport->init_event.connect(
519                 sigc::bind (
520                         mem_fun (*this, &MackieControlProtocol::handle_port_init)
521                         , sport
522                 )
523         );
524
525         connections_back = sport->active_event.connect(
526                 sigc::bind (
527                         mem_fun (*this, &MackieControlProtocol::handle_port_changed)
528                         , sport
529                         , true
530                 )
531         );
532
533         connections_back = sport->inactive_event.connect(
534                 sigc::bind (
535                         mem_fun (*this, &MackieControlProtocol::handle_port_changed)
536                         , sport
537                         , false
538                 )
539         );
540         
541         _ports_changed = true;
542 }
543
544 void MackieControlProtocol::create_ports()
545 {
546         MIDI::Manager * mm = MIDI::Manager::instance();
547
548         // open main port
549         {
550                 MIDI::Port * midi_port = mm->port( default_port_name );
551
552                 if ( midi_port == 0 ) {
553                         ostringstream os;
554                         os << string_compose( _("no MIDI port named \"%1\" exists - Mackie control disabled"), default_port_name );
555                         error << os.str() << endmsg;
556                         throw MackieControlException( os.str() );
557                 }
558                 add_port( *midi_port, 0 );
559         }
560         
561         // open extender ports. Up to 9. Should be enough.
562         // could also use mm->get_midi_ports()
563         string ext_port_base = "mcu_xt_";
564         for ( int index = 1; index <= 9; ++index )
565         {
566                 ostringstream os;
567                 os << ext_port_base << index;
568                 MIDI::Port * midi_port = mm->port( os.str() );
569                 if ( midi_port != 0 ) add_port( *midi_port, index );
570         }
571 }
572
573 shared_ptr<Route> MackieControlProtocol::master_route()
574 {
575         shared_ptr<Route> retval;
576         retval = session->route_by_name( "master" );
577         if ( retval == 0 )
578         {
579                 // TODO search through all routes for one with the master attribute set
580         }
581         return retval;
582 }
583
584 Strip & MackieControlProtocol::master_strip()
585 {
586         return dynamic_cast<Strip&>( *surface().groups["master"] );
587 }
588
589 void MackieControlProtocol::initialize_surface()
590 {
591         // set up the route table
592         int strips = 0;
593         for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
594         {
595                 strips += (*it)->strips();
596         }
597         
598         set_route_table_size( strips );
599         
600         switch ( mcu_port().emulation() )
601         {
602                 case MackiePort::bcf2000: _surface = new BcfSurface( strips ); break;
603                 case MackiePort::mackie: _surface = new MackieSurface( strips ); break;
604                 default:
605                         ostringstream os;
606                         os << "no Surface class found for emulation: " << mcu_port().emulation();
607                         throw MackieControlException( os.str() );
608         }
609         _surface->init();
610         
611         // Connect events. Must be after route table otherwise there will be trouble
612         for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
613         {
614                 (*it)->control_event.connect( ( mem_fun (*this, &MackieControlProtocol::handle_control_event) ) );
615         }
616 }
617
618 void MackieControlProtocol::close()
619 {
620         // TODO disconnect port active/inactive signals
621         // Or at least put a lock here
622         
623         if ( _surface != 0 )
624         {
625                 // These will fail if the port has gone away.
626                 // So catch the exception and do the rest of the
627                 // close afterwards
628                 // because the bcf doesn't respond to the next 3 sysex messages
629                 try
630                 {
631                         zero_all();
632                 }
633                 catch ( exception & e )
634                 {
635                         cout << "MackieControlProtocol::close caught exception: " << e.what() << endl;
636                 }
637                 
638                 for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
639                 {
640                         try
641                         {
642                                 MackiePort & port = **it;
643                                 // faders to minimum
644                                 port.write_sysex( 0x61 );
645                                 // All LEDs off
646                                 port.write_sysex( 0x62 );
647                                 // Reset (reboot into offline mode)
648                                 port.write_sysex( 0x63 );
649                         }
650                         catch ( exception & e )
651                         {
652                                 cout << "MackieControlProtocol::close caught exception: " << e.what() << endl;
653                         }
654                 }
655                 
656                 // disconnect global signals from Session
657                 // TODO Since *this is a sigc::trackable, this shouldn't be necessary
658                 for( vector<sigc::connection>::iterator it = _connections.begin(); it != _connections.end(); ++it )
659                 {
660                         it->disconnect();
661                 }
662                 
663                 // disconnect routes from strips
664                 clear_route_signals();
665         }
666         
667         // stop polling, and wait for it...
668         pthread_cancel_one( thread );
669         pthread_join( thread, 0 );
670         
671         // shut down MackiePorts
672         for( MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it )
673         {
674                 delete *it;
675         }
676         _ports.clear();
677         
678         delete[] pfd;
679 }
680
681 void* MackieControlProtocol::_monitor_work (void* arg)
682 {
683         return static_cast<MackieControlProtocol*>(arg)->monitor_work ();
684 }
685
686 XMLNode & MackieControlProtocol::get_state()
687 {
688         cout << "MackieControlProtocol::get_state" << endl;
689         
690         // add name of protocol
691         XMLNode* node = new XMLNode( X_("Protocol") );
692         node->add_property( X_("name"), _name );
693         
694         // add current bank
695         ostringstream os;
696         os << _current_initial_bank;
697         node->add_property( X_("bank"), os.str() );
698         
699         return *node;
700 }
701
702 int MackieControlProtocol::set_state( const XMLNode & node )
703 {
704         cout << "MackieControlProtocol::set_state: active " << _active << endl;
705         int retval = 0;
706         
707         // fetch current bank
708         if ( node.property( X_("bank") ) != 0 )
709         {
710                 string bank = node.property( X_("bank") )->value();
711                 try
712                 {
713                         set_active( true );
714                         uint32_t new_bank = atoi( bank.c_str() );
715                         if ( _current_initial_bank != new_bank ) switch_banks( new_bank );
716                 }
717                 catch ( exception & e )
718                 {
719                         cout << "exception in MackieControlProtocol::set_state: " << e.what() << endl;
720                         return -1;
721                 }
722         }
723         
724         return retval;
725 }
726
727 void MackieControlProtocol::handle_control_event( SurfacePort & port, Control & control, const ControlState & state )
728 {
729         uint32_t index = control.ordinal() - 1 + ( port.number() * port.strips() );
730         boost::shared_ptr<Route> route;
731         if ( control.group().is_strip() )
732         {
733                 if ( control.group().is_master() )
734                 {
735                         route = master_route();
736                 }
737                 else if ( index < route_table.size() )
738                         route = route_table[index];
739                 else
740                         cerr << "Warning: index is " << index << " which is not in the route table, size: " << route_table.size() << endl;
741         }
742         
743         // This handles control element events from the surface
744         // the state of the controls on the surface is usually updated
745         // from UI events.
746         switch ( control.type() )
747         {
748                 case Control::type_fader:
749                         if ( control.group().is_strip() )
750                         {
751                                 // find the route in the route table for the id
752                                 // if the route isn't available, skip it
753                                 // at which point the fader should just reset itself
754                                 if ( route != 0 )
755                                 {
756                                         route->set_gain( slider_position_to_gain( state.pos ), this );
757                                         
758                                         // must echo bytes back to slider now, because
759                                         // the notifier only works if the fader is not being
760                                         // touched. Which it is if we're getting input.
761                                         port.write( builder.build_fader( (Fader&)control, state.pos ) );
762                                 }
763                         }
764                         else
765                         {
766                                 // master fader
767                                 boost::shared_ptr<Route> route = master_route();
768                                 if ( route )
769                                 {
770                                         route->set_gain( slider_position_to_gain( state.pos ), this );
771                                         port.write( builder.build_fader( (Fader&)control, state.pos ) );
772                                 }
773                         }
774                         break;
775                         
776                 case Control::type_button:
777                         if ( control.group().is_strip() )
778                         {
779                                 // strips
780                                 if ( route != 0 )
781                                 {
782                                         handle_strip_button( control, state.button_state, route );
783                                 }
784                                 else
785                                 {
786                                         // no route so always switch the light off
787                                         // because no signals will be emitted by a non-route
788                                         port.write( builder.build_led( control.led(), off ) );
789                                 }
790                         }
791                         else if ( control.group().is_master() )
792                         {
793                                 // master fader touch
794                                 boost::shared_ptr<Route> route = master_route();
795                                 if ( route )
796                                         handle_strip_button( control, state.button_state, route );
797                         }
798                         else
799                         {
800                                 // handle all non-strip buttons
801                                 surface().handle_button( *this, state.button_state, dynamic_cast<Button&>( control ) );
802                         }
803                         break;
804                         
805                 // pot (jog wheel, external control)
806                 case Control::type_pot:
807                         if ( control.group().is_strip() )
808                         {
809                                 if ( route != 0 )
810                                 {
811                                         if ( route->panner().size() == 1 )
812                                         {
813                                                 // assume pan for now
814                                                 float xpos;
815                                                 route->panner()[0]->get_effective_position (xpos);
816                                                 
817                                                 // calculate new value, and trim
818                                                 xpos += state.delta;
819                                                 if ( xpos > 1.0 )
820                                                         xpos = 1.0;
821                                                 else if ( xpos < 0.0 )
822                                                         xpos = 0.0;
823                                                 
824                                                 route->panner()[0]->set_position( xpos );
825                                         }
826                                 }
827                                 else
828                                 {
829                                         // it's a pot for an umnapped route, so turn all the lights off
830                                         port.write( builder.build_led_ring( dynamic_cast<Pot &>( control ), off ) );
831                                 }
832                         }
833                         else
834                         {
835                                 if ( control.name() == "jog" )
836                                 {
837                                         // TODO use current snap-to setting?
838                                         long delta = state.ticks * 1000;
839                                         nframes_t next = session->transport_frame() + delta;
840                                         if ( delta < 0 && session->transport_frame() < (nframes_t) abs( delta )  )
841                                         {
842                                                 next = session->current_start_frame();
843                                         }
844                                         else if ( next > session->current_end_frame() )
845                                         {
846                                                 next = session->current_end_frame();
847                                         }
848                                         
849                                         session->request_locate( next, session->transport_rolling() );
850                                         
851                                         // turn off the led ring, for bcf emulation mode
852                                         port.write( builder.build_led_ring( dynamic_cast<Pot &>( control ), off ) );
853                                 }
854                                 else
855                                 {
856                                         cout << "external controller" << state.ticks << endl;
857                                 }
858                         }
859                         break;
860                         
861                 default:
862                         cout << "Control::type not handled: " << control.type() << endl;
863         }
864 }
865
866 /////////////////////////////////////////////////////////
867 // Notifications from UI
868 /////////////////////////////////////////////////////////
869 struct RouteSignalByRoute
870 {
871         RouteSignalByRoute( Route & route ): _route( route ) {}
872                 
873         bool operator () ( const RouteSignal & rs ) const
874         {
875                 return rs.route().id() == _route.id();
876         }
877         
878         bool operator () ( const RouteSignal * rs ) const
879         {
880                 return rs->route().id() == _route.id();
881         }
882
883         Route & _route;
884 };
885
886 Strip & MackieControlProtocol::strip_from_route( Route * route )
887 {
888         if ( route == 0 )
889         {
890                 throw MackieControlException( "route is null in MackieControlProtocol::strip_from_route" );
891         }
892         
893         if ( route->master() )
894         {
895                 return master_strip();
896         }
897         
898         RouteSignals::iterator it = find_if(
899                 route_signals.begin()
900                 , route_signals.end()
901                 , RouteSignalByRoute( *route )
902         );
903         
904         if ( it == route_signals.end() )
905         {
906                 ostringstream os;
907                 os << "No strip for route " << route->name();
908                 throw MackieControlException( os.str() );
909         }
910         
911         return (*it)->strip();
912 }
913
914 /////////////////////////////////////////////////
915 // handlers for Route signals
916 // TODO should these be part of RouteSignal?
917 /////////////////////////////////////////////////
918
919 void MackieControlProtocol::notify_solo_changed( ARDOUR::Route * route, MackiePort * port )
920 {
921         try
922         {
923                 Button & button = strip_from_route( route ).solo();
924                 port->write( builder.build_led( button, route->soloed() ) );
925         }
926         catch( exception & e )
927         {
928                 cout << e.what() << endl;
929         }
930 }
931
932 void MackieControlProtocol::notify_mute_changed( ARDOUR::Route * route, MackiePort * port )
933 {
934         try
935         {
936                 Button & button = strip_from_route( route ).mute();
937                 port->write( builder.build_led( button, route->muted() ) );
938         }
939         catch( exception & e )
940         {
941                 cout << e.what() << endl;
942         }
943 }
944
945 void MackieControlProtocol::notify_record_enable_changed( ARDOUR::Route * route, MackiePort * port )
946 {
947         try
948         {
949                 Button & button = strip_from_route( route ).recenable();
950                 port->write( builder.build_led( button, route->record_enabled() ) );
951         }
952         catch( exception & e )
953         {
954                 cout << e.what() << endl;
955         }
956 }
957
958 void MackieControlProtocol::notify_gain_changed(  ARDOUR::Route * route, MackiePort * port )
959 {
960         try
961         {
962                 Fader & fader = strip_from_route( route ).gain();
963                 if ( !fader.touch() )
964                 {
965                         port->write( builder.build_fader( fader, gain_to_slider_position( route->gain() ) ) );
966                 }
967         }
968         catch( exception & e )
969         {
970                 cout << e.what() << endl;
971         }
972 }
973
974 void MackieControlProtocol::notify_name_changed( void *, ARDOUR::Route * route, MackiePort * port )
975 {
976         try
977         {
978                 // TODO implement MackieControlProtocol::notify_name_changed
979         }
980         catch( exception & e )
981         {
982                 cout << e.what() << endl;
983         }
984 }
985
986 // TODO deal with > 1 channel being panned
987 void MackieControlProtocol::notify_panner_changed( ARDOUR::Route * route, MackiePort * port )
988 {
989         try
990         {
991                 Pot & pot = strip_from_route( route ).vpot();
992                 if ( route->panner().size() == 1 )
993                 {
994                         float pos;
995                         route->panner()[0]->get_effective_position( pos);
996                         port->write( builder.build_led_ring( pot, ControlState( on, pos ) ) );
997                 }
998                 else
999                 {
1000                         port->write( builder.zero_control( pot ) );
1001                 }
1002         }
1003         catch( exception & e )
1004         {
1005                 cout << e.what() << endl;
1006         }
1007 }
1008
1009 /////////////////////////////////////
1010 // Transport Buttons
1011 /////////////////////////////////////
1012
1013 LedState MackieControlProtocol::rewind_press( Button & button )
1014 {
1015         // can use first_mark_before/after as well
1016         Location * loc = session->locations()->first_location_before (
1017                 session->transport_frame()
1018         );
1019         if ( loc != 0 ) session->request_locate( loc->start(), session->transport_rolling() );
1020         return on;
1021 }
1022
1023 LedState MackieControlProtocol::rewind_release( Button & button )
1024 {
1025         return off;
1026 }
1027
1028 LedState MackieControlProtocol::ffwd_press( Button & button )
1029 {
1030         // can use first_mark_before/after as well
1031         Location * loc = session->locations()->first_location_after (
1032                 session->transport_frame()
1033         );
1034         if ( loc != 0 ) session->request_locate( loc->start(), session->transport_rolling() );
1035         return on;
1036 }
1037
1038 LedState MackieControlProtocol::ffwd_release( Button & button )
1039 {
1040         return off;
1041 }
1042
1043 LedState MackieControlProtocol::stop_press( Button & button )
1044 {
1045         session->request_stop();
1046         return on;
1047 }
1048
1049 LedState MackieControlProtocol::stop_release( Button & button )
1050 {
1051         return session->transport_stopped();
1052 }
1053
1054 LedState MackieControlProtocol::play_press( Button & button )
1055 {
1056         session->request_transport_speed( 1.0 );
1057         return on;
1058 }
1059
1060 LedState MackieControlProtocol::play_release( Button & button )
1061 {
1062         return session->transport_rolling();
1063 }
1064
1065 LedState MackieControlProtocol::record_press( Button & button )
1066 {
1067         if ( session->get_record_enabled() )
1068                 session->disable_record( false );
1069         else
1070                 session->maybe_enable_record();
1071         return on;
1072 }
1073
1074 LedState MackieControlProtocol::record_release( Button & button )
1075 {
1076         if ( session->get_record_enabled() )
1077         {
1078                 if ( session->transport_rolling() )
1079                         return on;
1080                 else
1081                         return flashing;
1082         }
1083         else
1084                 return off;
1085 }
1086
1087 ///////////////////////////////////////////
1088 // Session signals
1089 ///////////////////////////////////////////
1090
1091 void MackieControlProtocol::notify_parameter_changed( const char * name_str )
1092 {
1093         string name( name_str );
1094         if ( name == "punch-in" )
1095         {
1096                 update_global_button( "punch_in", Config->get_punch_in() );
1097         }
1098         else if ( name == "punch-out" )
1099         {
1100                 update_global_button( "punch_out", Config->get_punch_out() );
1101         }
1102 }
1103
1104 // RouteList is the set of routes that have just been added
1105 void MackieControlProtocol::notify_route_added( ARDOUR::Session::RouteList & rl )
1106 {
1107         // currently assigned banks are less than the full set of
1108         // strips, so activate the new strip now.
1109         if ( route_signals.size() < route_table.size() )
1110         {
1111                 refresh_current_bank();
1112         }
1113         // otherwise route added, but current bank needs no updating
1114 }
1115
1116 void MackieControlProtocol::notify_solo_active_changed( bool active )
1117 {
1118         Button * rude_solo = reinterpret_cast<Button*>( surface().controls_by_name["solo"] );
1119         mcu_port().write( builder.build_led( *rude_solo, active ? flashing : off ) );
1120 }
1121
1122 ///////////////////////////////////////////
1123 // Transport signals
1124 ///////////////////////////////////////////
1125
1126 void MackieControlProtocol::notify_record_state_changed()
1127 {
1128         // switch rec button on / off / flashing
1129         Button * rec = reinterpret_cast<Button*>( surface().controls_by_name["record"] );
1130         mcu_port().write( builder.build_led( *rec, record_release( *rec ) ) );
1131 }
1132
1133 void MackieControlProtocol::notify_transport_state_changed()
1134 {
1135         // switch various play and stop buttons on / off
1136         update_global_button( "play", session->transport_rolling() );
1137         update_global_button( "stop", !session->transport_rolling() );
1138         update_global_button( "loop", session->get_play_loop() );
1139         
1140         // rec is special because it's tristate
1141         Button * rec = reinterpret_cast<Button*>( surface().controls_by_name["record"] );
1142         mcu_port().write( builder.build_led( *rec, record_release( *rec ) ) );
1143 }
1144
1145 LedState MackieControlProtocol::loop_press( Button & button )
1146 {
1147         session->request_play_loop( !session->get_play_loop() );
1148         return on;
1149 }
1150
1151 LedState MackieControlProtocol::loop_release( Button & button )
1152 {
1153         return session->get_play_loop();
1154 }
1155
1156 LedState MackieControlProtocol::punch_in_press( Button & button )
1157 {
1158         bool state = !Config->get_punch_in();
1159         Config->set_punch_in( state );
1160         return state;
1161 }
1162
1163 LedState MackieControlProtocol::punch_in_release( Button & button )
1164 {
1165         return Config->get_punch_in();
1166 }
1167
1168 LedState MackieControlProtocol::punch_out_press( Button & button )
1169 {
1170         bool state = !Config->get_punch_out();
1171         Config->set_punch_out( state );
1172         return state;
1173 }
1174
1175 LedState MackieControlProtocol::punch_out_release( Button & button )
1176 {
1177         return Config->get_punch_out();
1178 }
1179
1180 LedState MackieControlProtocol::home_press( Button & button )
1181 {
1182         session->goto_start();
1183         return on;
1184 }
1185
1186 LedState MackieControlProtocol::home_release( Button & button )
1187 {
1188         return off;
1189 }
1190
1191 LedState MackieControlProtocol::end_press( Button & button )
1192 {
1193         session->goto_end();
1194         return on;
1195 }
1196
1197 LedState MackieControlProtocol::end_release( Button & button )
1198 {
1199         return off;
1200 }
1201
1202 /////////////////////////////////////
1203 // Bank Switching
1204 /////////////////////////////////////
1205 LedState MackieControlProtocol::left_press( Button & button )
1206 {
1207         Sorted sorted = get_sorted_routes();
1208         if ( sorted.size() > route_table.size() )
1209         {
1210                 int new_initial = _current_initial_bank - route_table.size();
1211                 if ( new_initial < 0 ) new_initial = 0;
1212                 if ( new_initial != int( _current_initial_bank ) )
1213                 {
1214                         session->set_dirty();
1215                         switch_banks( new_initial );
1216                 }
1217                 
1218                 return on;
1219         }
1220         else
1221         {
1222                 return flashing;
1223         }
1224 }
1225
1226 LedState MackieControlProtocol::left_release( Button & button )
1227 {
1228         return off;
1229 }
1230
1231 LedState MackieControlProtocol::right_press( Button & button )
1232 {
1233         Sorted sorted = get_sorted_routes();
1234         if ( sorted.size() > route_table.size() )
1235         {
1236                 uint32_t delta = sorted.size() - ( route_table.size() + _current_initial_bank );
1237                 if ( delta > route_table.size() ) delta = route_table.size();
1238                 if ( delta > 0 )
1239                 {
1240                         session->set_dirty();
1241                         switch_banks( _current_initial_bank + delta );
1242                 }
1243                 
1244                 return on;
1245         }
1246         else
1247         {
1248                 return flashing;
1249         }
1250 }
1251
1252 LedState MackieControlProtocol::right_release( Button & button )
1253 {
1254         return off;
1255 }
1256
1257 LedState MackieControlProtocol::channel_left_press( Button & button )
1258 {
1259         Sorted sorted = get_sorted_routes();
1260         if ( sorted.size() > route_table.size() )
1261         {
1262                 prev_track();
1263                 return on;
1264         }
1265         else
1266         {
1267                 return flashing;
1268         }
1269 }
1270
1271 LedState MackieControlProtocol::channel_left_release( Button & button )
1272 {
1273         return off;
1274 }
1275
1276 LedState MackieControlProtocol::channel_right_press( Button & button )
1277 {
1278         Sorted sorted = get_sorted_routes();
1279         if ( sorted.size() > route_table.size() )
1280         {
1281                 next_track();
1282                 return on;
1283         }
1284         else
1285         {
1286                 return flashing;
1287         }
1288 }
1289
1290 LedState MackieControlProtocol::channel_right_release( Button & button )
1291 {
1292         return off;
1293 }