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