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