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