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