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