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