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