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