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