merge fix
[ardour.git] / libs / ardour / session_transport.cc
1 /*
2     Copyright (C) 1999-2003 Paul Davis
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 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
23
24 #include <cmath>
25 #include <cerrno>
26 #include <unistd.h>
27
28 #include "pbd/undo.h"
29 #include "pbd/error.h"
30 #include "pbd/enumwriter.h"
31 #include "pbd/pthread_utils.h"
32 #include "pbd/memento_command.h"
33 #include "pbd/stacktrace.h"
34
35 #include "midi++/mmc.h"
36 #include "midi++/port.h"
37
38 #include "ardour/audioengine.h"
39 #include "ardour/auditioner.h"
40 #include "ardour/butler.h"
41 #include "ardour/click.h"
42 #include "ardour/debug.h"
43 #include "ardour/location.h"
44 #include "ardour/profile.h"
45 #include "ardour/scene_changer.h"
46 #include "ardour/session.h"
47 #include "ardour/slave.h"
48 #include "ardour/operations.h"
49
50 #include "i18n.h"
51
52 using namespace std;
53 using namespace ARDOUR;
54 using namespace PBD;
55
56 void
57 Session::add_post_transport_work (PostTransportWork ptw)
58 {
59         PostTransportWork oldval;
60         PostTransportWork newval;
61         int tries = 0;
62
63         while (tries < 8) {
64                 oldval = (PostTransportWork) g_atomic_int_get (&_post_transport_work);
65                 newval = PostTransportWork (oldval | ptw);
66                 if (g_atomic_int_compare_and_exchange (&_post_transport_work, oldval, newval)) {
67                         /* success */
68                         return;
69                 }
70         }
71
72         error << "Could not set post transport work! Crazy thread madness, call the programmers" << endmsg;
73 }
74
75 void
76 Session::request_input_change_handling ()
77 {
78         if (!(_state_of_the_state & (InitialConnecting|Deletion))) {
79                 SessionEvent* ev = new SessionEvent (SessionEvent::InputConfigurationChange, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
80                 queue_event (ev);
81         }
82 }
83
84 void
85 Session::request_sync_source (Slave* new_slave)
86 {
87         SessionEvent* ev = new SessionEvent (SessionEvent::SetSyncSource, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
88         bool seamless;
89
90         seamless = Config->get_seamless_loop ();
91
92         if (dynamic_cast<Engine_Slave*>(new_slave)) {
93                 /* JACK cannot support seamless looping at present */
94                 Config->set_seamless_loop (false);
95         } else {
96                 /* reset to whatever the value was before we last switched slaves */
97                 Config->set_seamless_loop (_was_seamless);
98         }
99
100         /* save value of seamless from before the switch */
101         _was_seamless = seamless;
102
103         ev->slave = new_slave;
104         DEBUG_TRACE (DEBUG::Slave, "sent request for new slave\n");
105         queue_event (ev);
106 }
107
108 void
109 Session::request_transport_speed (double speed, bool as_default)
110 {
111         SessionEvent* ev = new SessionEvent (SessionEvent::SetTransportSpeed, SessionEvent::Add, SessionEvent::Immediate, 0, speed);
112         ev->third_yes_or_no = true;
113         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request transport speed = %1 as default = %2\n", speed, as_default));
114         queue_event (ev);
115 }
116
117 /** Request a new transport speed, but if the speed parameter is exactly zero then use
118  *  a very small +ve value to prevent the transport actually stopping.  This method should
119  *  be used by callers who are varying transport speed but don't ever want to stop it.
120  */
121 void
122 Session::request_transport_speed_nonzero (double speed, bool as_default)
123 {
124         if (speed == 0) {
125                 speed = DBL_EPSILON;
126         }
127
128         request_transport_speed (speed, as_default);
129 }
130
131 void
132 Session::request_track_speed (Track* tr, double speed)
133 {
134         SessionEvent* ev = new SessionEvent (SessionEvent::SetTrackSpeed, SessionEvent::Add, SessionEvent::Immediate, 0, speed);
135         ev->set_ptr (tr);
136         queue_event (ev);
137 }
138
139 void
140 Session::request_stop (bool abort, bool clear_state)
141 {
142         SessionEvent* ev = new SessionEvent (SessionEvent::SetTransportSpeed, SessionEvent::Add, SessionEvent::Immediate, audible_frame(), 0.0, abort, clear_state);
143         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request transport stop, audible %3 transport %4 abort = %1, clear state = %2\n", abort, clear_state, audible_frame(), _transport_frame));
144         queue_event (ev);
145 }
146
147 void
148 Session::request_locate (framepos_t target_frame, bool with_roll)
149 {
150         SessionEvent *ev = new SessionEvent (with_roll ? SessionEvent::LocateRoll : SessionEvent::Locate, SessionEvent::Add, SessionEvent::Immediate, target_frame, 0, false);
151         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request locate to %1\n", target_frame));
152         queue_event (ev);
153 }
154
155 void
156 Session::force_locate (framepos_t target_frame, bool with_roll)
157 {
158         SessionEvent *ev = new SessionEvent (with_roll ? SessionEvent::LocateRoll : SessionEvent::Locate, SessionEvent::Add, SessionEvent::Immediate, target_frame, 0, true);
159         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request forced locate to %1\n", target_frame));
160         queue_event (ev);
161 }
162
163 void
164 Session::request_play_loop (bool yn, bool change_transport_roll)
165 {
166         SessionEvent* ev;
167         Location *location = _locations->auto_loop_location();
168         double target_speed;
169
170         if (location == 0 && yn) {
171                 error << _("Cannot loop - no loop range defined")
172                       << endmsg;
173                 return;
174         }
175
176         if (change_transport_roll) {
177                 if (transport_rolling()) {
178                         /* start looping at current speed */
179                         target_speed = transport_speed ();
180                 } else {
181                         /* currently stopped */
182                         if (yn) {
183                                 /* start looping at normal speed */
184                                 target_speed = 1.0;
185                         } else {
186                                 target_speed = 0.0;
187                         }
188                 }
189         } else {
190                 /* leave the speed alone */
191                 target_speed = transport_speed ();
192         }
193
194         ev = new SessionEvent (SessionEvent::SetLoop, SessionEvent::Add, SessionEvent::Immediate, 0, target_speed, yn);
195         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request set loop = %1, change roll state ? %2\n", yn, change_transport_roll));
196         queue_event (ev);
197
198         if (yn) {
199                 if (!change_transport_roll) {
200                         if (!transport_rolling()) {
201                                 /* we're not changing transport state, but we do want
202                                    to set up position for the new loop. Don't
203                                    do this if we're rolling already.
204                                 */
205                                 request_locate (location->start(), false);
206                         }
207                 }
208         } else {
209                 if (!change_transport_roll && Config->get_seamless_loop() && transport_rolling()) {
210                         // request an immediate locate to refresh the tracks
211                         // after disabling looping
212                         request_locate (_transport_frame-1, false);
213                 }
214         }
215 }
216
217 void
218 Session::request_play_range (list<AudioRange>* range, bool leave_rolling)
219 {
220         SessionEvent* ev = new SessionEvent (SessionEvent::SetPlayAudioRange, SessionEvent::Add, SessionEvent::Immediate, 0, (leave_rolling ? 1.0 : 0.0));
221         if (range) {
222                 ev->audio_range = *range;
223         } else {
224                 ev->audio_range.clear ();
225         }
226         DEBUG_TRACE (DEBUG::Transport, string_compose ("Request play range, leave rolling ? %1\n", leave_rolling));
227         queue_event (ev);
228 }
229
230 void
231 Session::request_cancel_play_range ()
232 {
233         SessionEvent* ev = new SessionEvent (SessionEvent::CancelPlayAudioRange, SessionEvent::Add, SessionEvent::Immediate, 0, 0);
234         queue_event (ev);
235 }
236
237
238 void
239 Session::realtime_stop (bool abort, bool clear_state)
240 {
241         DEBUG_TRACE (DEBUG::Transport, string_compose ("realtime stop @ %1\n", _transport_frame));
242         PostTransportWork todo = PostTransportWork (0);
243
244         /* assume that when we start, we'll be moving forwards */
245
246         if (_transport_speed < 0.0f) {
247                 todo = (PostTransportWork (todo | PostTransportStop | PostTransportReverse));
248                 _default_transport_speed = 1.0;
249         } else {
250                 todo = PostTransportWork (todo | PostTransportStop);
251         }
252
253         /* call routes */
254
255         boost::shared_ptr<RouteList> r = routes.reader ();
256
257         for (RouteList::iterator i = r->begin (); i != r->end(); ++i) {
258                 (*i)->realtime_handle_transport_stopped ();
259         }
260         
261         DEBUG_TRACE (DEBUG::Transport, string_compose ("stop complete, auto-return scheduled for return to %1\n", _requested_return_frame));
262
263         /* the duration change is not guaranteed to have happened, but is likely */
264         
265         todo = PostTransportWork (todo | PostTransportDuration);
266
267         if (abort) {
268                 todo = PostTransportWork (todo | PostTransportAbort);
269         }
270
271         if (clear_state) {
272                 todo = PostTransportWork (todo | PostTransportClearSubstate);
273         }
274
275         if (todo) {
276                 add_post_transport_work (todo);
277         }
278
279         _clear_event_type (SessionEvent::StopOnce);
280         _clear_event_type (SessionEvent::RangeStop);
281         _clear_event_type (SessionEvent::RangeLocate);
282
283         /* if we're going to clear loop state, then force disabling record BUT only if we're not doing latched rec-enable */
284         disable_record (true, (!Config->get_latched_record_enable() && clear_state));
285
286         reset_slave_state ();
287
288         _transport_speed = 0;
289         _target_transport_speed = 0;
290
291         g_atomic_int_set (&_playback_load, 100);
292         g_atomic_int_set (&_capture_load, 100);
293
294         if (config.get_use_video_sync()) {
295                 waiting_for_sync_offset = true;
296         }
297
298         transport_sub_state = 0;
299 }
300
301 void
302 Session::realtime_locate ()
303 {
304         boost::shared_ptr<RouteList> r = routes.reader ();
305         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
306                 (*i)->realtime_locate ();
307         }
308 }
309
310 void
311 Session::butler_transport_work ()
312 {
313   restart:
314         bool finished;
315         PostTransportWork ptw;
316         boost::shared_ptr<RouteList> r = routes.reader ();
317         uint64_t before;
318         
319         int on_entry = g_atomic_int_get (&_butler->should_do_transport_work);
320         finished = true;
321         ptw = post_transport_work();
322
323         DEBUG_TRACE (DEBUG::Transport, string_compose ("Butler transport work, todo = %1 at %2\n", enum_2_string (ptw), (before = g_get_monotonic_time())));
324
325         if (ptw & PostTransportAdjustPlaybackBuffering) {
326                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
327                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
328                         if (tr) {
329                                 tr->adjust_playback_buffering ();
330                                 /* and refill those buffers ... */
331                         }
332                         (*i)->non_realtime_locate (_transport_frame);
333                 }
334
335         }
336
337         if (ptw & PostTransportAdjustCaptureBuffering) {
338                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
339                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
340                         if (tr) {
341                                 tr->adjust_capture_buffering ();
342                         }
343                 }
344         }
345
346         if (ptw & PostTransportCurveRealloc) {
347                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
348                         (*i)->curve_reallocate();
349                 }
350         }
351
352         if (ptw & PostTransportInputChange) {
353                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
354                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
355                         if (tr) {
356                                 tr->non_realtime_input_change ();
357                         }
358                 }
359         }
360
361         if (ptw & PostTransportSpeed) {
362                 non_realtime_set_speed ();
363         }
364
365         if (ptw & PostTransportReverse) {
366
367                 clear_clicks();
368                 cumulative_rf_motion = 0;
369                 reset_rf_scale (0);
370
371                 /* don't seek if locate will take care of that in non_realtime_stop() */
372
373                 if (!(ptw & PostTransportLocate)) {
374
375                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
376                                 (*i)->non_realtime_locate (_transport_frame);
377
378                                 if (on_entry != g_atomic_int_get (&_butler->should_do_transport_work)) {
379                                         /* new request, stop seeking, and start again */
380                                         g_atomic_int_dec_and_test (&_butler->should_do_transport_work);
381                                         goto restart;
382                                 }
383                         }
384                 }
385         }
386
387         if (ptw & PostTransportLocate) {
388                 DEBUG_TRACE (DEBUG::Transport, "nonrealtime locate invoked from BTW\n");
389                 non_realtime_locate ();
390         }
391
392         if (ptw & PostTransportStop) {
393                 non_realtime_stop (ptw & PostTransportAbort, on_entry, finished);
394                 if (!finished) {
395                         g_atomic_int_dec_and_test (&_butler->should_do_transport_work);
396                         goto restart;
397                 }
398         }
399
400         if (ptw & PostTransportOverWrite) {
401                 non_realtime_overwrite (on_entry, finished);
402                 if (!finished) {
403                         g_atomic_int_dec_and_test (&_butler->should_do_transport_work);
404                         goto restart;
405                 }
406         }
407
408         if (ptw & PostTransportAudition) {
409                 non_realtime_set_audition ();
410         }
411
412         g_atomic_int_dec_and_test (&_butler->should_do_transport_work);
413
414         DEBUG_TRACE (DEBUG::Transport, string_compose (X_("Butler transport work all done after %1 usecs\n"), g_get_monotonic_time() - before));
415         DEBUG_TRACE (DEBUG::Transport, X_(string_compose ("Frame %1\n", _transport_frame)));
416 }
417
418 void
419 Session::non_realtime_set_speed ()
420 {
421         boost::shared_ptr<RouteList> rl = routes.reader();
422         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
423                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
424                 if (tr) {
425                         tr->non_realtime_set_speed ();
426                 }
427         }
428 }
429
430 void
431 Session::non_realtime_overwrite (int on_entry, bool& finished)
432 {
433         boost::shared_ptr<RouteList> rl = routes.reader();
434         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
435                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
436                 if (tr && tr->pending_overwrite ()) {
437                         tr->overwrite_existing_buffers ();
438                 }
439                 if (on_entry != g_atomic_int_get (&_butler->should_do_transport_work)) {
440                         finished = false;
441                         return;
442                 }
443         }
444 }
445
446
447 void
448 Session::non_realtime_locate ()
449 {
450         DEBUG_TRACE (DEBUG::Transport, string_compose ("locate tracks to %1\n", _transport_frame));
451
452         if (Config->get_loop_is_mode() && get_play_loop()) {
453
454                 Location *loc  = _locations->auto_loop_location();
455
456                 if (!loc || (_transport_frame < loc->start() || _transport_frame >= loc->end())) {
457                         /* jumped out of loop range: stop tracks from looping,
458                            but leave loop (mode) enabled.
459                          */
460                         set_track_loop (false);
461
462                 } else if (loc && Config->get_seamless_loop() &&
463                    ((loc->start() <= _transport_frame) ||
464                    (loc->end() > _transport_frame) ) ) {
465
466                         /* jumping to start of loop. This  might have been done before but it is
467                          * idempotent and cheap. Doing it here ensures that when we start playback
468                          * outside the loop we still flip tracks into the magic seamless mode
469                          * when needed.
470                          */
471                         set_track_loop (true);
472
473                 } else if (loc) {
474                         set_track_loop (false);
475                 }
476                 
477         } else {
478
479                 /* no more looping .. should have been noticed elsewhere */
480         }
481
482         
483         boost::shared_ptr<RouteList> rl = routes.reader();
484         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
485                 (*i)->non_realtime_locate (_transport_frame);
486         }
487
488         _scene_changer->locate (_transport_frame);
489
490         /* XXX: it would be nice to generate the new clicks here (in the non-RT thread)
491            rather than clearing them so that the RT thread has to spend time constructing
492            them (in Session::click).
493          */
494         clear_clicks ();
495 }
496
497 #ifdef USE_TRACKS_CODE_FEATURES
498 bool
499 Session::select_playhead_priority_target (framepos_t& jump_to)
500 {
501         jump_to = -1;
502
503         AutoReturnTarget autoreturn = Config->get_auto_return_target_list ();
504
505         if (!autoreturn) {
506                 return false;
507         }
508
509         if (Profile->get_trx() && transport_rolling() ) {
510                 // We're playing, so do nothing.
511                 // Next stop will put us where we need to be.
512                 return false;
513         }
514         
515         /* Note that the order of checking each AutoReturnTarget flag defines
516            the priority each flag.
517
518            Ardour/Mixbus: Last Locate
519                           Range Selection
520                           Loop Range
521                           Region Selection
522
523            Tracks:        Range Selection
524                           Loop Range
525                           Region Selection
526                           Last Locate
527         */
528         
529         if (autoreturn & RangeSelectionStart) {
530                 if (!_range_selection.empty()) {
531                         jump_to = _range_selection.from;
532                 } else {
533                         if (transport_rolling ()) {
534                                 /* Range selection no longer exists, but we're playing,
535                                    so do nothing. Next stop will put us where
536                                    we need to be.
537                                 */
538                                 return false;
539                         }
540                 }
541         }
542         
543         if (jump_to < 0 && (autoreturn & Loop) && get_play_loop()) {
544                 /* don't try to handle loop play when synced to JACK */
545                 
546                 if (!synced_to_engine()) {
547                         Location *location = _locations->auto_loop_location();
548                         
549                         if (location) {
550                                 jump_to = location->start();
551
552                                 if (Config->get_seamless_loop()) {
553                                         /* need to get track buffers reloaded */
554                                         set_track_loop (true);
555                                 }
556                         } 
557                 }
558         }
559         
560         if (jump_to < 0 && (autoreturn & RegionSelectionStart)) {
561                 if (!_object_selection.empty()) {
562                         jump_to = _object_selection.from;
563                 }
564         } 
565
566         if (jump_to < 0 && (autoreturn & LastLocate)) {
567                 jump_to = _last_roll_location;
568         }
569         
570         return jump_to >= 0;
571 }
572 #else
573
574 bool
575 Session::select_playhead_priority_target (framepos_t& jump_to)
576 {
577         if (!config.get_auto_return()) {
578                 return false;
579         }
580
581         jump_to = _last_roll_location;
582         return jump_to >= 0;
583 }
584
585 #endif
586
587 void
588 Session::follow_playhead_priority ()
589 {
590         framepos_t target;
591
592         if (select_playhead_priority_target (target)) {
593                 request_locate (target);
594         }
595 }
596
597 void
598 Session::non_realtime_stop (bool abort, int on_entry, bool& finished)
599 {
600         struct tm* now;
601         time_t     xnow;
602         bool       did_record;
603         bool       saved;
604         PostTransportWork ptw = post_transport_work();
605
606         did_record = false;
607         saved = false;
608
609         boost::shared_ptr<RouteList> rl = routes.reader();
610         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
611                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
612                 if (tr && tr->get_captured_frames () != 0) {
613                         did_record = true;
614                         break;
615                 }
616         }
617
618         /* stop and locate are merged here because they share a lot of common stuff */
619
620         time (&xnow);
621         now = localtime (&xnow);
622
623         if (auditioner) {
624                 auditioner->cancel_audition ();
625         }
626
627         cumulative_rf_motion = 0;
628         reset_rf_scale (0);
629
630         if (did_record) {
631                 begin_reversible_command (Operations::capture);
632                 _have_captured = true;
633         }
634
635         DEBUG_TRACE (DEBUG::Transport, X_("Butler PTW: DS stop\n"));
636
637         if (abort && did_record) {
638                 /* no reason to save the session file when we remove sources
639                  */
640                 _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
641         }
642
643         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
644                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
645                 if (tr) {
646                         tr->transport_stopped_wallclock (*now, xnow, abort);
647                 }
648         }
649
650         if (abort && did_record) {
651                 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
652         }
653
654         boost::shared_ptr<RouteList> r = routes.reader ();
655
656         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
657                 if (!(*i)->is_auditioner()) {
658                         (*i)->set_pending_declick (0);
659                 }
660         }
661
662         if (did_record) {
663                 commit_reversible_command ();
664                 /* increase take name */
665                 if (config.get_track_name_take () && !config.get_take_name ().empty()) {
666                         string newname = config.get_take_name();
667                         config.set_take_name(bump_name_number (newname));
668                 }
669         }
670
671         if (_engine.running()) {
672                 PostTransportWork ptw = post_transport_work ();
673                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
674                         (*i)->nonrealtime_handle_transport_stopped (abort, (ptw & PostTransportLocate), (!(ptw & PostTransportLocate) || pending_locate_flush));
675                 }
676                 update_latency_compensation ();
677         }
678
679         bool const auto_return_enabled = (!config.get_external_sync() && (Config->get_auto_return_target_list() || abort));
680
681         if (auto_return_enabled ||
682             (ptw & PostTransportLocate) ||
683             (_requested_return_frame >= 0) ||
684             synced_to_engine()) {
685
686                 if (pending_locate_flush) {
687                         flush_all_inserts ();
688                 }
689
690                 if ((auto_return_enabled || synced_to_engine() || _requested_return_frame >= 0) &&
691                     !(ptw & PostTransportLocate)) {
692
693                         /* no explicit locate queued */
694
695                         bool do_locate = false;
696
697                         if (_requested_return_frame >= 0) {
698
699                                 /* explicit return request pre-queued in event list. overrides everything else */
700
701                                 _transport_frame = _requested_return_frame;
702                                 do_locate = true;
703
704                         } else {
705                                 framepos_t jump_to;
706
707                                 if (select_playhead_priority_target (jump_to)) {
708
709                                         _transport_frame = jump_to;
710                                         do_locate = true;
711
712                                 } else if (abort) {
713
714                                         _transport_frame = _last_roll_location;
715                                         do_locate = true;
716                                 }
717                         }
718
719                         _requested_return_frame = -1;
720
721                         if (do_locate) {
722                                 _engine.transport_locate (_transport_frame);
723                         }
724                 }
725
726         }
727
728         clear_clicks();
729
730         /* do this before seeking, because otherwise the tracks will do the wrong thing in seamless loop mode.
731         */
732
733         if (ptw & PostTransportClearSubstate) {
734                 unset_play_range ();
735                 if (!Config->get_loop_is_mode()) {
736                         unset_play_loop ();
737                 }
738         }
739
740         /* this for() block can be put inside the previous if() and has the effect of ... ??? what */
741
742         DEBUG_TRACE (DEBUG::Transport, X_("Butler PTW: locate\n"));
743         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
744                 DEBUG_TRACE (DEBUG::Transport, string_compose ("Butler PTW: locate on %1\n", (*i)->name()));
745                 (*i)->non_realtime_locate (_transport_frame);
746
747                 if (on_entry != g_atomic_int_get (&_butler->should_do_transport_work)) {
748                         finished = false;
749                         /* we will be back */
750                         return;
751                 }
752         }
753
754         have_looped = false;
755
756         /* don't bother with this stuff if we're disconnected from the engine,
757            because there will be no process callbacks to deliver stuff from
758         */
759
760         if (_engine.connected() && !_engine.freewheeling()) {
761                 // need to queue this in the next RT cycle
762                 _send_timecode_update = true;
763                 
764                 if (!dynamic_cast<MTC_Slave*>(_slave)) {
765                         send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdStop));
766
767                         /* This (::non_realtime_stop()) gets called by main
768                            process thread, which will lead to confusion
769                            when calling AsyncMIDIPort::write().
770                            
771                            Something must be done. XXX
772                         */
773                         send_mmc_locate (_transport_frame);
774                 }
775         }
776
777         if ((ptw & PostTransportLocate) && get_record_enabled()) {
778                 /* This is scheduled by realtime_stop(), which is also done
779                  * when a slave requests /locate/ for an initial sync.
780                  * We can't hold up the slave for long with a save() here,
781                  * without breaking its initial sync cycle.
782                  *
783                  * save state only if there's no slave or if it's not yet locked.
784                  */
785                 if (!_slave || !_slave->locked()) {
786                         DEBUG_TRACE (DEBUG::Transport, X_("Butler PTW: requests save\n"));
787                         SaveSessionRequested (_current_snapshot_name);
788                         saved = true;
789                 }
790         }
791
792         /* always try to get rid of this */
793
794         remove_pending_capture_state ();
795
796         /* save the current state of things if appropriate */
797
798         if (did_record && !saved) {
799                 SaveSessionRequested (_current_snapshot_name);
800         }
801
802         if (ptw & PostTransportStop) {
803                 unset_play_range ();
804                 if (!Config->get_loop_is_mode()) {
805                         unset_play_loop ();
806                 }
807         }
808
809         PositionChanged (_transport_frame); /* EMIT SIGNAL */
810         DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC with speed = %1\n", _transport_speed));
811         TransportStateChange (); /* EMIT SIGNAL */
812
813         /* and start it up again if relevant */
814
815         if ((ptw & PostTransportLocate) && !config.get_external_sync() && pending_locate_roll) {
816                 request_transport_speed (1.0);
817         }
818
819         /* Even if we didn't do a pending locate roll this time, we don't want it hanging
820            around for next time.
821         */
822         pending_locate_roll = false;
823 }
824
825 void
826 Session::check_declick_out ()
827 {
828         bool locate_required = transport_sub_state & PendingLocate;
829
830         /* this is called after a process() iteration. if PendingDeclickOut was set,
831            it means that we were waiting to declick the output (which has just been
832            done) before maybe doing something else. this is where we do that "something else".
833
834            note: called from the audio thread.
835         */
836
837         if (transport_sub_state & PendingDeclickOut) {
838
839                 if (locate_required) {
840                         start_locate (pending_locate_frame, pending_locate_roll, pending_locate_flush);
841                         transport_sub_state &= ~(PendingDeclickOut|PendingLocate);
842                 } else {
843                         if (!(transport_sub_state & StopPendingCapture)) {
844                                 stop_transport (pending_abort);
845                                 transport_sub_state &= ~(PendingDeclickOut|PendingLocate);
846                         }
847                 }
848
849         } else if (transport_sub_state & PendingLoopDeclickOut) {
850                 /* Nothing else to do here; we've declicked, and the loop event will be along shortly */
851                 transport_sub_state &= ~PendingLoopDeclickOut;
852         }
853 }
854
855 void
856 Session::unset_play_loop ()
857 {
858         if (play_loop) {
859                 play_loop = false;
860                 clear_events (SessionEvent::AutoLoop);
861                 clear_events (SessionEvent::AutoLoopDeclick);
862                 set_track_loop (false);
863                 
864         
865                 if (Config->get_seamless_loop()) {
866                         /* likely need to flush track buffers: this will locate us to wherever we are */
867                         add_post_transport_work (PostTransportLocate);
868                         _butler->schedule_transport_work ();
869                 }
870         }
871 }
872
873 void
874 Session::set_track_loop (bool yn)
875 {
876         Location* loc = _locations->auto_loop_location ();
877
878         if (!loc) {
879                 yn = false;
880         }
881
882         boost::shared_ptr<RouteList> rl = routes.reader ();
883
884         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
885                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
886                 if (tr && !tr->hidden()) {
887                         tr->set_loop (yn ? loc : 0);
888                 }
889         }
890 }
891
892 void
893 Session::set_play_loop (bool yn, double speed)
894 {
895         /* Called from event-handling context */
896
897         Location *loc;
898
899         if (yn == play_loop || (actively_recording() && yn) || (loc = _locations->auto_loop_location()) == 0) {
900                 /* nothing to do, or can't change loop status while recording */
901                 return;
902         }
903
904         if (yn && Config->get_seamless_loop() && synced_to_engine()) {
905                 warning << string_compose (
906                         _("Seamless looping cannot be supported while %1 is using JACK transport.\n"
907                           "Recommend changing the configured options"), PROGRAM_NAME)
908                         << endmsg;
909                 return;
910         }
911
912         if (yn) {
913
914                 play_loop = true;
915                 have_looped = false;
916                 
917                 if (loc) {
918
919                         unset_play_range ();
920
921                         if (Config->get_seamless_loop()) {
922                                 if (!Config->get_loop_is_mode()) {
923                                         /* set all tracks to use internal looping */
924                                         set_track_loop (true);
925                                 } else {
926                                         /* we will do this in the locate to the start OR when we hit the end 
927                                          * of the loop for the first time 
928                                          */
929                                 }
930                         } else {
931                                 /* set all tracks to NOT use internal looping */
932                                 set_track_loop (false);
933                         }
934
935                         /* Put the delick and loop events in into the event list.  The declick event will
936                            cause a de-clicking fade-out just before the end of the loop, and it will also result
937                            in a fade-in when the loop restarts.  The AutoLoop event will peform the actual loop.
938                         */
939
940                         framepos_t dcp;
941                         framecnt_t dcl;
942                         auto_loop_declick_range (loc, dcp, dcl);
943                         merge_event (new SessionEvent (SessionEvent::AutoLoopDeclick, SessionEvent::Replace, dcp, dcl, 0.0f));
944                         merge_event (new SessionEvent (SessionEvent::AutoLoop, SessionEvent::Replace, loc->end(), loc->start(), 0.0f));
945
946                         /* if requested to roll, locate to start of loop and
947                          * roll but ONLY if we're not already rolling.
948
949                            args: positition, roll=true, flush=true, with_loop=false, force buffer refill if seamless looping
950                         */
951
952                         if (Config->get_loop_is_mode()) {
953                                 /* loop IS a transport mode: if already
954                                    rolling, do not locate to loop start.
955                                 */
956                                 if (!transport_rolling() && (speed != 0.0)) {
957                                         start_locate (loc->start(), true, true, false, Config->get_seamless_loop());
958                                 }
959                         } else {
960                                 if (speed != 0.0) {
961                                         start_locate (loc->start(), true, true, false, Config->get_seamless_loop());
962                                 }
963                         }
964                 }
965
966         } else {
967
968                 unset_play_loop ();
969         }
970
971         DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC2 with speed = %1\n", _transport_speed));
972         TransportStateChange ();
973 }
974 void
975 Session::flush_all_inserts ()
976 {
977         boost::shared_ptr<RouteList> r = routes.reader ();
978
979         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
980                 (*i)->flush_processors ();
981         }
982 }
983
984 void
985 Session::start_locate (framepos_t target_frame, bool with_roll, bool with_flush, bool with_loop, bool force)
986 {
987         if (target_frame < 0) {
988                 error << _("Locate called for negative sample position - ignored") << endmsg;
989                 return;
990         }
991
992         if (synced_to_engine()) {
993
994                 double sp;
995                 framepos_t pos;
996
997                 _slave->speed_and_position (sp, pos);
998
999                 if (target_frame != pos) {
1000
1001                         if (config.get_jack_time_master()) {
1002                                 /* actually locate now, since otherwise jack_timebase_callback
1003                                    will use the incorrect _transport_frame and report an old
1004                                    and incorrect time to Jack transport
1005                                 */
1006                                 locate (target_frame, with_roll, with_flush, with_loop, force);
1007                         }
1008
1009                         /* tell JACK to change transport position, and we will
1010                            follow along later in ::follow_slave()
1011                         */
1012
1013                         _engine.transport_locate (target_frame);
1014
1015                         if (sp != 1.0f && with_roll) {
1016                                 _engine.transport_start ();
1017                         }
1018
1019                 }
1020
1021         } else {
1022                 locate (target_frame, with_roll, with_flush, with_loop, force);
1023         }
1024 }
1025
1026 int
1027 Session::micro_locate (framecnt_t distance)
1028 {
1029         boost::shared_ptr<RouteList> rl = routes.reader();
1030         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1031                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1032                 if (tr && !tr->can_internal_playback_seek (distance)) {
1033                         return -1;
1034                 }
1035         }
1036
1037         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1038                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1039                 if (tr) {
1040                         tr->internal_playback_seek (distance);
1041                 }
1042         }
1043
1044         _transport_frame += distance;
1045         return 0;
1046 }
1047
1048 /** @param with_mmc true to send a MMC locate command when the locate is done */
1049 void
1050 Session::locate (framepos_t target_frame, bool with_roll, bool with_flush, bool for_seamless_loop, bool force, bool with_mmc)
1051 {
1052         bool need_butler = false;
1053         
1054         /* Locates for seamless looping are fairly different from other
1055          * locates. They assume that the diskstream buffers for each track
1056          * already have the correct data in them, and thus there is no need to
1057          * actually tell the tracks to locate. What does need to be done,
1058          * though, is all the housekeeping that is associated with non-linear
1059          * changes in the value of _transport_frame. 
1060          */
1061
1062         DEBUG_TRACE (DEBUG::Transport, string_compose ("rt-locate to %1, roll %2 flush %3 seamless %4 force %5 mmc %6\n",
1063                                                        target_frame, with_roll, with_flush, for_seamless_loop, force, with_mmc));
1064         
1065         if (actively_recording() && !for_seamless_loop) {
1066                 return;
1067         }
1068
1069         if (!force && _transport_frame == target_frame && !loop_changing && !for_seamless_loop) {
1070                 if (with_roll) {
1071                         set_transport_speed (1.0, 0, false);
1072                 }
1073                 loop_changing = false;
1074                 Located (); /* EMIT SIGNAL */
1075                 return;
1076         }
1077
1078         if (_transport_speed && !for_seamless_loop) {
1079                 /* Schedule a declick.  We'll be called again when its done.
1080                    We only do it this way for ordinary locates, not those
1081                    due to **seamless** loops.
1082                 */
1083
1084                 if (!(transport_sub_state & PendingDeclickOut)) {
1085                         transport_sub_state |= (PendingDeclickOut|PendingLocate);
1086                         pending_locate_frame = target_frame;
1087                         pending_locate_roll = with_roll;
1088                         pending_locate_flush = with_flush;
1089                         return;
1090                 }
1091         }
1092
1093         // Update Timecode time
1094         // [DR] FIXME: find out exactly where this should go below
1095         _transport_frame = target_frame;
1096         _last_roll_or_reversal_location = target_frame;
1097         timecode_time(_transport_frame, transmitting_timecode_time);
1098         outbound_mtc_timecode_frame = _transport_frame;
1099         next_quarter_frame_to_send = 0;
1100
1101         /* do "stopped" stuff if:
1102          *
1103          * we are rolling AND
1104          *    no autoplay in effect AND
1105          *       we're not going to keep rolling after the locate AND
1106          *           !(playing a loop with JACK sync)
1107          *
1108          */
1109
1110         bool transport_was_stopped = !transport_rolling();
1111
1112         if (transport_was_stopped && (!auto_play_legal || !config.get_auto_play()) && !with_roll && !(synced_to_engine() && play_loop) &&
1113             (!Profile->get_trx() || !(config.get_external_sync() && !synced_to_engine()))) {
1114                 realtime_stop (false, true); // XXX paul - check if the 2nd arg is really correct
1115                 transport_was_stopped = true;
1116         } else {
1117                 /* otherwise tell the world that we located */
1118                 realtime_locate ();
1119         }
1120
1121         if (force || !for_seamless_loop || loop_changing) {
1122
1123                 PostTransportWork todo = PostTransportLocate;
1124
1125                 if (with_roll && transport_was_stopped) {
1126                         todo = PostTransportWork (todo | PostTransportRoll);
1127                 }
1128
1129                 add_post_transport_work (todo);
1130                 need_butler = true;
1131                 
1132         } else {
1133
1134                 /* this is functionally what clear_clicks() does but with a tentative lock */
1135
1136                 Glib::Threads::RWLock::WriterLock clickm (click_lock, Glib::Threads::TRY_LOCK);
1137
1138                 if (clickm.locked()) {
1139
1140                         for (Clicks::iterator i = clicks.begin(); i != clicks.end(); ++i) {
1141                                 delete *i;
1142                         }
1143
1144                         clicks.clear ();
1145                 }
1146         }
1147
1148         if (with_roll) {
1149                 /* switch from input if we're going to roll */
1150                 if (Config->get_monitoring_model() == HardwareMonitoring) {
1151                         set_track_monitor_input_status (!config.get_auto_input());
1152                 }
1153         } else {
1154                 /* otherwise we're going to stop, so do the opposite */
1155                 if (Config->get_monitoring_model() == HardwareMonitoring) {
1156                         set_track_monitor_input_status (true);
1157                 }
1158         }
1159
1160         /* cancel looped playback if transport pos outside of loop range */
1161         if (play_loop) {
1162
1163                 Location* al = _locations->auto_loop_location();
1164
1165                 if (al) {
1166                         if (_transport_frame < al->start() || _transport_frame > al->end()) {
1167
1168                                 // located outside the loop: cancel looping directly, this is called from event handling context
1169
1170                                 have_looped = false;
1171                                 
1172                                 if (!Config->get_loop_is_mode()) {
1173                                         set_play_loop (false, _transport_speed);
1174                                 } else {
1175                                         if (Config->get_seamless_loop()) {
1176                                                 /* this will make the non_realtime_locate() in the butler
1177                                                    which then causes seek() in tracks actually do the right
1178                                                    thing.
1179                                                 */
1180                                                 set_track_loop (false);
1181                                         }
1182                                 }
1183                                 
1184                         } else if (_transport_frame == al->start()) {
1185
1186                                 // located to start of loop - this is looping, basically
1187
1188                                 if (for_seamless_loop) {
1189
1190                                         if (!have_looped) {
1191                                                 /* first time */
1192                                                 if (_last_roll_location != al->start()) {
1193                                                         /* didn't start at loop start - playback must have
1194                                                          * started before loop since we've now hit the loop
1195                                                          * end.
1196                                                          */
1197                                                         add_post_transport_work (PostTransportLocate);
1198                                                         need_butler = true;
1199                                                 }
1200                                                     
1201                                         }
1202                                 
1203                                         // this is only necessary for seamless looping
1204                                         
1205                                         boost::shared_ptr<RouteList> rl = routes.reader();
1206
1207                                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1208                                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1209
1210                                                 if (tr && tr->record_enabled ()) {
1211                                                         // tell it we've looped, so it can deal with the record state
1212                                                         tr->transport_looped (_transport_frame);
1213                                                 }
1214                                         }
1215                                 }
1216
1217                                 have_looped = true;
1218                                 TransportLooped(); // EMIT SIGNAL
1219                         }
1220                 }
1221         }
1222
1223         if (need_butler) {
1224                 _butler->schedule_transport_work ();
1225         }
1226
1227         loop_changing = false;
1228
1229         _send_timecode_update = true;
1230
1231         if (with_mmc) {
1232                 send_mmc_locate (_transport_frame);
1233         }
1234
1235         _last_roll_location = _last_roll_or_reversal_location =  _transport_frame;
1236         Located (); /* EMIT SIGNAL */
1237 }
1238
1239 /** Set the transport speed.
1240  *  Called from the process thread.
1241  *  @param speed New speed
1242  */
1243 void
1244 Session::set_transport_speed (double speed, framepos_t destination_frame, bool abort, bool clear_state, bool as_default)
1245 {
1246         DEBUG_TRACE (DEBUG::Transport, string_compose ("@ %5 Set transport speed to %1, abort = %2 clear_state = %3, current = %4 as_default %6\n", 
1247                                                        speed, abort, clear_state, _transport_speed, _transport_frame, as_default));
1248
1249         if (_transport_speed == speed) {
1250                 if (as_default && speed == 0.0) { // => reset default transport speed. hacky or what?
1251                         _default_transport_speed = 1.0;
1252                 }
1253                 return;
1254         }
1255
1256         if (actively_recording() && speed != 1.0 && speed != 0.0) {
1257                 /* no varispeed during recording */
1258                 DEBUG_TRACE (DEBUG::Transport, string_compose ("No varispeed during recording cur_speed %1, frame %2\n", 
1259                                                        _transport_speed, _transport_frame));
1260                 return;
1261         }
1262
1263         _target_transport_speed = fabs(speed);
1264
1265         /* 8.0 max speed is somewhat arbitrary but based on guestimates regarding disk i/o capability
1266            and user needs. We really need CD-style "skip" playback for ffwd and rewind.
1267         */
1268
1269         if (speed > 0) {
1270                 speed = min (8.0, speed);
1271         } else if (speed < 0) {
1272                 speed = max (-8.0, speed);
1273         }
1274
1275         if (transport_rolling() && speed == 0.0) {
1276
1277                 /* we are rolling and we want to stop */
1278
1279                 if (Config->get_monitoring_model() == HardwareMonitoring) {
1280                         set_track_monitor_input_status (true);
1281                 }
1282                 
1283                 if (synced_to_engine ()) {
1284                         if (clear_state) {
1285                                 /* do this here because our response to the slave won't
1286                                    take care of it.
1287                                 */
1288                                 _play_range = false;
1289                                 unset_play_loop ();
1290                         }
1291                         _engine.transport_stop ();
1292                 } else {
1293                         bool const auto_return_enabled = (!config.get_external_sync() && (Config->get_auto_return_target_list() || abort));
1294
1295                         if (!auto_return_enabled) {
1296                                 _requested_return_frame = destination_frame;
1297                         }
1298
1299                         stop_transport (abort);
1300                 }
1301
1302                 if (!Config->get_loop_is_mode()) {
1303                         unset_play_loop ();
1304                 }
1305
1306         } else if (transport_stopped() && speed == 1.0) {
1307
1308                 /* we are stopped and we want to start rolling at speed 1 */
1309
1310                 if (Config->get_loop_is_mode() && play_loop) {
1311
1312                         Location *location = _locations->auto_loop_location();
1313                         
1314                         if (location != 0) {
1315                                 if (_transport_frame != location->start()) {
1316
1317                                         if (Config->get_seamless_loop()) {
1318                                                 /* force tracks to do their thing */
1319                                                 set_track_loop (true);
1320                                         }
1321
1322                                         /* jump to start and then roll from there */
1323
1324                                         request_locate (location->start(), true);
1325                                         return;
1326                                 }
1327                         }
1328                 }
1329
1330                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1331                         set_track_monitor_input_status (false);
1332                 }
1333
1334                 if (synced_to_engine()) {
1335                         _engine.transport_start ();
1336                 } else {
1337                         start_transport ();
1338                 }
1339
1340         } else {
1341
1342                 /* not zero, not 1.0 ... varispeed */
1343
1344                 if ((synced_to_engine()) && speed != 0.0 && speed != 1.0) {
1345                         warning << string_compose (
1346                                 _("Global varispeed cannot be supported while %1 is connected to JACK transport control"),
1347                                 PROGRAM_NAME)
1348                                 << endmsg;
1349                         return;
1350                 }
1351
1352                 if (actively_recording()) {
1353                         return;
1354                 }
1355
1356                 if (speed > 0.0 && _transport_frame == current_end_frame()) {
1357                         return;
1358                 }
1359
1360                 if (speed < 0.0 && _transport_frame == 0) {
1361                         return;
1362                 }
1363
1364                 clear_clicks ();
1365
1366                 /* if we are reversing relative to the current speed, or relative to the speed
1367                    before the last stop, then we have to do extra work.
1368                 */
1369
1370                 PostTransportWork todo = PostTransportWork (0);
1371
1372                 if ((_transport_speed && speed * _transport_speed < 0.0) || (_last_transport_speed * speed < 0.0) || (_last_transport_speed == 0.0f && speed < 0.0f)) {
1373                         todo = PostTransportWork (todo | PostTransportReverse);
1374                         _last_roll_or_reversal_location = _transport_frame;
1375                 }
1376
1377                 _last_transport_speed = _transport_speed;
1378                 _transport_speed = speed;
1379
1380                 if (as_default) {
1381                         _default_transport_speed = speed;
1382                 }
1383
1384                 boost::shared_ptr<RouteList> rl = routes.reader();
1385                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1386                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1387                         if (tr && tr->realtime_set_speed (tr->speed(), true)) {
1388                                 todo = PostTransportWork (todo | PostTransportSpeed);
1389                         }
1390                 }
1391
1392                 if (todo) {
1393                         add_post_transport_work (todo);
1394                         _butler->schedule_transport_work ();
1395                 }
1396
1397                 DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC3 with speed = %1\n", _transport_speed));
1398
1399                 /* throttle signal emissions. 
1400                  * when slaved [_last]_transport_speed
1401                  * usually changes every cycle (tiny amounts due to DLL).
1402                  * Emitting a signal every cycle is overkill and unwarranted.
1403                  *
1404                  * Using _last_transport_speed is not acceptable,
1405                  * since it allows for large changes over a long period 
1406                  * of time. Hence we introduce a dedicated variable to keep track
1407                  *
1408                  * The 0.2% dead-zone is somewhat arbitrary. Main use-case
1409                  * for TransportStateChange() here is the ShuttleControl display.
1410                  */
1411                 if (fabsf(_signalled_varispeed - speed) > .002f
1412                     // still, signal hard changes to 1.0 and 0.0:
1413                     || ( speed == 1.f && _signalled_varispeed != 1.f)
1414                     || ( speed == 0.f && _signalled_varispeed != 0.f)
1415                    )
1416                 {
1417                         TransportStateChange (); /* EMIT SIGNAL */
1418                         _signalled_varispeed = speed;
1419                 }
1420         }
1421 }
1422
1423
1424 /** Stop the transport.  */
1425 void
1426 Session::stop_transport (bool abort, bool clear_state)
1427 {
1428         if (_transport_speed == 0.0f) {
1429                 return;
1430         }
1431
1432         if (!get_transport_declick_required()) {
1433
1434                 /* stop has not yet been scheduled */
1435
1436                 boost::shared_ptr<RouteList> rl = routes.reader();
1437                 framepos_t stop_target = audible_frame();
1438
1439                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1440                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1441                         if (tr) {
1442                                 tr->prepare_to_stop (_transport_frame, stop_target);
1443                         }
1444                 }
1445
1446                 SubState new_bits;
1447                 
1448                 if (actively_recording() &&                           /* we are recording */
1449                     worst_input_latency() > current_block_size) {     /* input latency exceeds block size, so simple 1 cycle delay before stop is not enough */
1450                         
1451                         /* we need to capture the audio that is still somewhere in the pipeline between
1452                            wherever it was generated and the process callback. This means that even though
1453                            the user (or something else)  has asked us to stop, we have to roll
1454                            past this point and then reset the playhead/transport location to
1455                            the position at which the stop was requested.
1456
1457                            we still need playback to "stop" now, however, which is why we schedule
1458                            a declick below.
1459                         */
1460                         
1461                         DEBUG_TRACE (DEBUG::Transport, string_compose ("stop transport requested @ %1, scheduled for + %2 = %3, abort = %4\n",
1462                                                                        _transport_frame, _worst_input_latency,
1463                                                                        _transport_frame + _worst_input_latency,
1464                                                                        abort));
1465                         
1466                         SessionEvent *ev = new SessionEvent (SessionEvent::StopOnce, SessionEvent::Replace,
1467                                                              _transport_frame + _worst_input_latency,
1468                                                              0, 0, abort);
1469                         
1470                         merge_event (ev);
1471
1472                         /* request a declick at the start of the next process cycle() so that playback ceases.
1473                            It will remain silent until we actually stop (at the StopOnce event somewhere in 
1474                            the future). The extra flag (StopPendingCapture) is set to ensure that check_declick_out()
1475                            does not stop the transport too early.
1476                          */
1477                         new_bits = SubState (PendingDeclickOut|StopPendingCapture);
1478                         
1479                 } else {
1480                         
1481                         /* Not recording, schedule a declick in the next process() cycle and then stop at its end */
1482                         
1483                         new_bits = PendingDeclickOut;
1484                 }
1485
1486                 
1487                 /* we'll be called again after the declick */
1488                 transport_sub_state = SubState (transport_sub_state|new_bits);
1489                 pending_abort = abort;
1490
1491                 return;
1492
1493         } else {
1494                 
1495                 /* declick was scheduled, but we've been called again, which means it is really time to stop
1496                    
1497                    XXX: we should probably split this off into its own method and call it explicitly.
1498                 */
1499
1500                 realtime_stop (abort, clear_state);
1501                 _butler->schedule_transport_work ();
1502         }
1503 }
1504
1505 /** Called from the process thread */
1506 void
1507 Session::start_transport ()
1508 {
1509         DEBUG_TRACE (DEBUG::Transport, "start_transport\n");
1510
1511         _last_roll_location = _transport_frame;
1512         _last_roll_or_reversal_location = _transport_frame;
1513
1514         have_looped = false;
1515
1516         /* if record status is Enabled, move it to Recording. if its
1517            already Recording, move it to Disabled.
1518         */
1519
1520         switch (record_status()) {
1521         case Enabled:
1522                 if (!config.get_punch_in()) {
1523                         enable_record ();
1524                 }
1525                 break;
1526
1527         case Recording:
1528                 if (!play_loop) {
1529                         disable_record (false);
1530                 }
1531                 break;
1532
1533         default:
1534                 break;
1535         }
1536
1537         transport_sub_state |= PendingDeclickIn;
1538
1539         _transport_speed = _default_transport_speed;
1540         _target_transport_speed = _transport_speed;
1541
1542         boost::shared_ptr<RouteList> rl = routes.reader();
1543         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1544                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1545                 if (tr) {
1546                         tr->realtime_set_speed (tr->speed(), true);
1547                 }
1548         }
1549
1550         if (!_engine.freewheeling()) {
1551                 Timecode::Time time;
1552                 timecode_time_subframes (_transport_frame, time);
1553                 if (!dynamic_cast<MTC_Slave*>(_slave)) {
1554                         send_immediate_mmc (MIDI::MachineControlCommand (MIDI::MachineControl::cmdDeferredPlay));
1555                 }
1556         }
1557
1558         DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC4 with speed = %1\n", _transport_speed));
1559         TransportStateChange (); /* EMIT SIGNAL */
1560 }
1561
1562 /** Do any transport work in the audio thread that needs to be done after the
1563  * transport thread is finished.  Audio thread, realtime safe.
1564  */
1565 void
1566 Session::post_transport ()
1567 {
1568         PostTransportWork ptw = post_transport_work ();
1569
1570         if (ptw & PostTransportAudition) {
1571                 if (auditioner && auditioner->auditioning()) {
1572                         process_function = &Session::process_audition;
1573                 } else {
1574                         process_function = &Session::process_with_events;
1575                 }
1576         }
1577
1578         if (ptw & PostTransportStop) {
1579
1580                 transport_sub_state = 0;
1581         }
1582
1583         if (ptw & PostTransportLocate) {
1584
1585                 if (((!config.get_external_sync() && (auto_play_legal && config.get_auto_play())) && !_exporting) || (ptw & PostTransportRoll)) {
1586                         start_transport ();
1587                 } else {
1588                         transport_sub_state = 0;
1589                 }
1590         }
1591
1592         set_next_event ();
1593         /* XXX is this really safe? shouldn't we just be unsetting the bits that we actually
1594            know were handled ?
1595         */
1596         set_post_transport_work (PostTransportWork (0));
1597 }
1598
1599 void
1600 Session::reset_rf_scale (framecnt_t motion)
1601 {
1602         cumulative_rf_motion += motion;
1603
1604         if (cumulative_rf_motion < 4 * _current_frame_rate) {
1605                 rf_scale = 1;
1606         } else if (cumulative_rf_motion < 8 * _current_frame_rate) {
1607                 rf_scale = 4;
1608         } else if (cumulative_rf_motion < 16 * _current_frame_rate) {
1609                 rf_scale = 10;
1610         } else {
1611                 rf_scale = 100;
1612         }
1613
1614         if (motion != 0) {
1615                 set_dirty();
1616         }
1617 }
1618
1619 void
1620 Session::mtc_status_changed (bool yn)
1621 {
1622         g_atomic_int_set (&_mtc_active, yn);
1623         MTCSyncStateChanged( yn );
1624 }
1625
1626 void
1627 Session::ltc_status_changed (bool yn)
1628 {
1629         g_atomic_int_set (&_ltc_active, yn);
1630         LTCSyncStateChanged( yn );
1631 }
1632
1633 void
1634 Session::use_sync_source (Slave* new_slave)
1635 {
1636         /* Runs in process() context */
1637
1638         bool non_rt_required = false;
1639
1640         /* XXX this deletion is problematic because we're in RT context */
1641
1642         delete _slave;
1643         _slave = new_slave;
1644
1645         MTC_Slave* mtc_slave = dynamic_cast<MTC_Slave*>(_slave);
1646         if (mtc_slave) {
1647                 mtc_slave->ActiveChanged.connect_same_thread (mtc_status_connection, boost::bind (&Session::mtc_status_changed, this, _1));
1648                 MTCSyncStateChanged(mtc_slave->locked() );
1649         } else {
1650                 if (g_atomic_int_get (&_mtc_active) ){
1651                         g_atomic_int_set (&_mtc_active, 0);
1652                         MTCSyncStateChanged( false );
1653                 }
1654                 mtc_status_connection.disconnect ();
1655         }
1656
1657         LTC_Slave* ltc_slave = dynamic_cast<LTC_Slave*> (_slave);
1658         if (ltc_slave) {
1659                 ltc_slave->ActiveChanged.connect_same_thread (ltc_status_connection, boost::bind (&Session::ltc_status_changed, this, _1));
1660                 LTCSyncStateChanged (ltc_slave->locked() );
1661         } else {
1662                 if (g_atomic_int_get (&_ltc_active) ){
1663                         g_atomic_int_set (&_ltc_active, 0);
1664                         LTCSyncStateChanged( false );
1665                 }
1666                 ltc_status_connection.disconnect ();
1667         }
1668
1669         DEBUG_TRACE (DEBUG::Slave, string_compose ("set new slave to %1\n", _slave));
1670         
1671         // need to queue this for next process() cycle
1672         _send_timecode_update = true;
1673
1674         boost::shared_ptr<RouteList> rl = routes.reader();
1675         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1676                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1677                 if (tr && !tr->hidden()) {
1678                         if (tr->realtime_set_speed (tr->speed(), true)) {
1679                                 non_rt_required = true;
1680                         }
1681                         tr->set_slaved (_slave != 0);
1682                 }
1683         }
1684
1685         if (non_rt_required) {
1686                 add_post_transport_work (PostTransportSpeed);
1687                 _butler->schedule_transport_work ();
1688         }
1689
1690         set_dirty();
1691 }
1692
1693 void
1694 Session::drop_sync_source ()
1695 {
1696         request_sync_source (0);
1697 }
1698
1699 void
1700 Session::switch_to_sync_source (SyncSource src)
1701 {
1702         Slave* new_slave;
1703
1704         DEBUG_TRACE (DEBUG::Slave, string_compose ("Setting up sync source %1\n", enum_2_string (src)));
1705
1706         switch (src) {
1707         case MTC:
1708                 if (_slave && dynamic_cast<MTC_Slave*>(_slave)) {
1709                         return;
1710                 }
1711
1712                 try {
1713                         new_slave = new MTC_Slave (*this, *_midi_ports->mtc_input_port());
1714                 }
1715
1716                 catch (failed_constructor& err) {
1717                         return;
1718                 }
1719                 break;
1720
1721         case LTC:
1722                 if (_slave && dynamic_cast<LTC_Slave*>(_slave)) {
1723                         return;
1724                 }
1725
1726                 try {
1727                         new_slave = new LTC_Slave (*this);
1728                 }
1729
1730                 catch (failed_constructor& err) {
1731                         return;
1732                 }
1733
1734                 break;
1735
1736         case MIDIClock:
1737                 if (_slave && dynamic_cast<MIDIClock_Slave*>(_slave)) {
1738                         return;
1739                 }
1740
1741                 try {
1742                         new_slave = new MIDIClock_Slave (*this, *_midi_ports->midi_clock_input_port(), 24);
1743                 }
1744
1745                 catch (failed_constructor& err) {
1746                         return;
1747                 }
1748                 break;
1749
1750         case Engine:
1751                 if (_slave && dynamic_cast<Engine_Slave*>(_slave)) {
1752                         return;
1753                 }
1754
1755                 if (config.get_video_pullup() != 0.0f) {
1756                         return;
1757                 }
1758
1759                 new_slave = new Engine_Slave (*AudioEngine::instance());
1760                 break;
1761
1762         default:
1763                 new_slave = 0;
1764                 break;
1765         };
1766
1767         request_sync_source (new_slave);
1768 }
1769
1770 void
1771 Session::set_track_speed (Track* track, double speed)
1772 {
1773         if (track->realtime_set_speed (speed, false)) {
1774                 add_post_transport_work (PostTransportSpeed);
1775                 _butler->schedule_transport_work ();
1776                 set_dirty ();
1777         }
1778 }
1779
1780 void
1781 Session::unset_play_range ()
1782 {
1783         _play_range = false;
1784         _clear_event_type (SessionEvent::RangeStop);
1785         _clear_event_type (SessionEvent::RangeLocate);
1786 }
1787
1788 void
1789 Session::set_play_range (list<AudioRange>& range, bool leave_rolling)
1790 {
1791         SessionEvent* ev;
1792
1793         /* Called from event-processing context */
1794
1795         unset_play_range ();
1796
1797         if (range.empty()) {
1798                 /* _play_range set to false in unset_play_range()
1799                  */
1800                 if (!leave_rolling) {
1801                         /* stop transport */
1802                         SessionEvent* ev = new SessionEvent (SessionEvent::SetTransportSpeed, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0f, false);
1803                         merge_event (ev);
1804                 }
1805                 return;
1806         }
1807
1808         _play_range = true;
1809
1810         /* cancel loop play */
1811         unset_play_loop ();
1812
1813         list<AudioRange>::size_type sz = range.size();
1814
1815         if (sz > 1) {
1816
1817                 list<AudioRange>::iterator i = range.begin();
1818                 list<AudioRange>::iterator next;
1819
1820                 while (i != range.end()) {
1821
1822                         next = i;
1823                         ++next;
1824
1825                         /* locating/stopping is subject to delays for declicking.
1826                          */
1827
1828                         framepos_t requested_frame = i->end;
1829
1830                         if (requested_frame > current_block_size) {
1831                                 requested_frame -= current_block_size;
1832                         } else {
1833                                 requested_frame = 0;
1834                         }
1835
1836                         if (next == range.end()) {
1837                                 ev = new SessionEvent (SessionEvent::RangeStop, SessionEvent::Add, requested_frame, 0, 0.0f);
1838                         } else {
1839                                 ev = new SessionEvent (SessionEvent::RangeLocate, SessionEvent::Add, requested_frame, (*next).start, 0.0f);
1840                         }
1841
1842                         merge_event (ev);
1843
1844                         i = next;
1845                 }
1846
1847         } else if (sz == 1) {
1848
1849                 ev = new SessionEvent (SessionEvent::RangeStop, SessionEvent::Add, range.front().end, 0, 0.0f);
1850                 merge_event (ev);
1851
1852         }
1853
1854         /* save range so we can do auto-return etc. */
1855
1856         current_audio_range = range;
1857
1858         /* now start rolling at the right place */
1859
1860         ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, SessionEvent::Immediate, range.front().start, 0.0f, false);
1861         merge_event (ev);
1862
1863         DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC5 with speed = %1\n", _transport_speed));
1864         TransportStateChange ();
1865 }
1866
1867 void
1868 Session::request_bounded_roll (framepos_t start, framepos_t end)
1869 {
1870         AudioRange ar (start, end, 0);
1871         list<AudioRange> lar;
1872
1873         lar.push_back (ar);
1874         request_play_range (&lar, true);
1875 }
1876
1877 void
1878 Session::set_requested_return_frame (framepos_t return_to)
1879 {
1880         _requested_return_frame = return_to;
1881 }
1882
1883 void
1884 Session::request_roll_at_and_return (framepos_t start, framepos_t return_to)
1885 {
1886         SessionEvent *ev = new SessionEvent (SessionEvent::LocateRollLocate, SessionEvent::Add, SessionEvent::Immediate, return_to, 1.0);
1887         ev->target2_frame = start;
1888         queue_event (ev);
1889 }
1890
1891 void
1892 Session::engine_halted ()
1893 {
1894         bool ignored;
1895
1896         /* there will be no more calls to process(), so
1897            we'd better clean up for ourselves, right now.
1898
1899            but first, make sure the butler is out of
1900            the picture.
1901         */
1902
1903         if (_butler) {
1904                 _butler->stop ();
1905         }
1906
1907         realtime_stop (false, true);
1908         non_realtime_stop (false, 0, ignored);
1909         transport_sub_state = 0;
1910
1911         DEBUG_TRACE (DEBUG::Transport, string_compose ("send TSC6 with speed = %1\n", _transport_speed));
1912         TransportStateChange (); /* EMIT SIGNAL */
1913 }
1914
1915
1916 void
1917 Session::xrun_recovery ()
1918 {
1919         ++_xrun_count;
1920
1921         Xrun (_transport_frame); /* EMIT SIGNAL */
1922
1923         if (Config->get_stop_recording_on_xrun() && actively_recording()) {
1924
1925                 /* it didn't actually halt, but we need
1926                    to handle things in the same way.
1927                 */
1928
1929                 engine_halted();
1930         }
1931 }
1932
1933 void
1934 Session::route_processors_changed (RouteProcessorChange c)
1935 {
1936         if (ignore_route_processor_changes) {
1937                 return;
1938         }
1939
1940         if (c.type == RouteProcessorChange::MeterPointChange) {
1941                 set_dirty ();
1942                 return;
1943         }
1944
1945         if (c.type == RouteProcessorChange::RealTimeChange) {
1946                 set_dirty ();
1947                 return;
1948         }
1949
1950         update_latency_compensation ();
1951         resort_routes ();
1952
1953         set_dirty ();
1954 }
1955
1956 void
1957 Session::allow_auto_play (bool yn)
1958 {
1959         auto_play_legal = yn;
1960 }
1961
1962 bool
1963 Session::maybe_stop (framepos_t limit)
1964 {
1965         if ((_transport_speed > 0.0f && _transport_frame >= limit) || (_transport_speed < 0.0f && _transport_frame == 0)) {
1966                 if (synced_to_engine () && config.get_jack_time_master ()) {
1967                         _engine.transport_stop ();
1968                 } else if (!synced_to_engine ()) {
1969                         stop_transport ();
1970                 }
1971                 return true;
1972         }
1973         return false;
1974 }
1975
1976 void
1977 Session::send_mmc_locate (framepos_t t)
1978 {
1979         if (t < 0) {
1980                 return;
1981         }
1982
1983         if (!_engine.freewheeling()) {
1984                 Timecode::Time time;
1985                 timecode_time_subframes (t, time);
1986                 send_immediate_mmc (MIDI::MachineControlCommand (time));
1987         }
1988 }
1989
1990 /** Ask the transport to not send timecode until further notice.  The suspension
1991  *  will come into effect some finite time after this call, and timecode_transmission_suspended()
1992  *  should be checked by the caller to find out when.
1993  */
1994 void
1995 Session::request_suspend_timecode_transmission ()
1996 {
1997         SessionEvent* ev = new SessionEvent (SessionEvent::SetTimecodeTransmission, SessionEvent::Add, SessionEvent::Immediate, 0, 0, false);
1998         queue_event (ev);
1999 }
2000
2001 void
2002 Session::request_resume_timecode_transmission ()
2003 {
2004         SessionEvent* ev = new SessionEvent (SessionEvent::SetTimecodeTransmission, SessionEvent::Add, SessionEvent::Immediate, 0, 0, true);
2005         queue_event (ev);
2006 }
2007
2008 bool
2009 Session::timecode_transmission_suspended () const
2010 {
2011         return g_atomic_int_get (&_suspend_timecode_transmission) == 1;
2012 }