the "final" (??) fixes for transport state stuff before 2.8.4. y'all let me know...
[ardour.git] / libs / ardour / session_transport.cc
1 /*
2     Copyright (C) 1999-2009 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 #include <cmath>
21 #include <cerrno>
22 #include <unistd.h>
23
24 #include <sigc++/bind.h>
25 #include <sigc++/retype.h>
26
27 #include <pbd/undo.h>
28 #include <pbd/error.h>
29 #include <glibmm/thread.h>
30 #include <pbd/pthread_utils.h>
31 #include <pbd/memento_command.h>
32 #include <pbd/stacktrace.h>
33
34 #include <midi++/mmc.h>
35 #include <midi++/port.h>
36
37 #include <ardour/ardour.h>
38 #include <ardour/audioengine.h>
39 #include <ardour/session.h>
40 #include <ardour/audio_diskstream.h>
41 #include <ardour/auditioner.h>
42 #include <ardour/slave.h>
43 #include <ardour/location.h>
44
45 #include "i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace sigc;
50 using namespace PBD;
51
52 void
53 Session::request_input_change_handling ()
54 {
55         if (!(_state_of_the_state & (InitialConnecting|Deletion))) {
56                 Event* ev = new Event (Event::InputConfigurationChange, Event::Add, Event::Immediate, 0, 0.0);
57                 queue_event (ev);
58         } 
59 }
60
61 void
62 Session::request_slave_source (SlaveSource src)
63 {
64         Event* ev = new Event (Event::SetSlaveSource, Event::Add, Event::Immediate, 0, 0.0);
65         bool seamless;
66
67         seamless = Config->get_seamless_loop ();
68
69         if (src == JACK) {
70                 /* JACK cannot support seamless looping at present */
71                 Config->set_seamless_loop (false);
72         } else {
73                 /* reset to whatever the value was before we last switched slaves */
74                 Config->set_seamless_loop (_was_seamless);
75         }
76
77         /* save value of seamless from before the switch */
78         _was_seamless = seamless;
79
80         ev->slave = src;
81         queue_event (ev);
82 }
83
84 void
85 Session::request_transport_speed (float speed)
86 {
87         Event* ev = new Event (Event::SetTransportSpeed, Event::Add, Event::Immediate, 0, speed);
88         queue_event (ev);
89 }
90
91 void
92 Session::request_diskstream_speed (Diskstream& ds, float speed)
93 {
94         Event* ev = new Event (Event::SetDiskstreamSpeed, Event::Add, Event::Immediate, 0, speed);
95         ev->set_ptr (&ds);
96         queue_event (ev);
97 }
98
99 void
100 Session::request_stop (bool abort, bool clear_state)
101 {
102         Event* ev = new Event (Event::SetTransportSpeed, Event::Add, Event::Immediate, 0, 0.0, abort, clear_state);
103         queue_event (ev);
104 }
105
106 void
107 Session::request_locate (nframes_t target_frame, bool with_roll)
108 {
109         Event *ev = new Event (with_roll ? Event::LocateRoll : Event::Locate, Event::Add, Event::Immediate, target_frame, 0, false);
110         queue_event (ev);
111 }
112
113 void
114 Session::force_locate (nframes_t target_frame, bool with_roll)
115 {
116         Event *ev = new Event (with_roll ? Event::LocateRoll : Event::Locate, Event::Add, Event::Immediate, target_frame, 0, true);
117         queue_event (ev);
118 }
119
120 void
121 Session::request_play_loop (bool yn, bool leave_rolling)
122 {
123         Event* ev;      
124         Location *location = _locations.auto_loop_location();
125
126         if (location == 0 && yn) {
127                 error << _("Cannot loop - no loop range defined")
128                       << endmsg;
129                 return;
130         }
131
132         ev = new Event (Event::SetLoop, Event::Add, Event::Immediate, 0, (leave_rolling ? 1.0 : 0.0), yn);
133         queue_event (ev);
134
135         if (!leave_rolling && !yn && Config->get_seamless_loop() && transport_rolling()) {
136                 // request an immediate locate to refresh the diskstreams
137                 // after disabling looping
138                 request_locate (_transport_frame-1, false);
139         } 
140 }
141
142 void
143 Session::request_play_range (bool yn, bool leave_rolling)
144 {
145         Event* ev = new Event (Event::SetPlayRange, Event::Add, Event::Immediate, 0, (leave_rolling ? 1.0 : 0.0), yn);
146         queue_event (ev);
147 }
148
149 void
150 Session::realtime_stop (bool abort, bool clear_state)
151 {
152         PostTransportWork todo = PostTransportWork (0);
153         
154         /* assume that when we start, we'll be moving forwards */
155
156         if (_transport_speed < 0.0f) {
157                 todo = PostTransportWork (todo | PostTransportStop | PostTransportReverse);
158         } else {
159                 todo = PostTransportWork (todo | PostTransportStop);
160         }
161
162         if (actively_recording()) {
163
164                 /* move the transport position back to where the
165                    request for a stop was noticed. we rolled
166                    past that point to pick up delayed input.
167                 */
168
169 #ifndef LEAVE_TRANSPORT_UNADJUSTED
170                 decrement_transport_position (_worst_output_latency);
171 #endif
172
173                 /* the duration change is not guaranteed to have happened, but is likely */
174
175                 todo = PostTransportWork (todo | PostTransportDuration);
176         }
177
178         if (abort) {
179                 todo = PostTransportWork (todo | PostTransportAbort);
180         }
181
182         if (clear_state) {
183                 todo = PostTransportWork (todo | PostTransportClearSubstate);
184         }
185         
186         if (todo) {
187                 post_transport_work = PostTransportWork (post_transport_work | todo);
188         }
189                                                   
190         _clear_event_type (Event::StopOnce);
191         _clear_event_type (Event::RangeStop);
192         _clear_event_type (Event::RangeLocate);
193
194         disable_record (true);
195
196         reset_slave_state ();
197                 
198         _transport_speed = 0;
199
200         if (Config->get_use_video_sync()) {
201                 waiting_for_sync_offset = true;
202         }
203
204         transport_sub_state = ((Config->get_slave_source() == None && Config->get_auto_return()) ? AutoReturning : 0);
205 }
206
207 void
208 Session::butler_transport_work ()
209 {
210   restart:
211         bool finished;
212         boost::shared_ptr<RouteList> r = routes.reader ();
213         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
214
215         int on_entry = g_atomic_int_get (&butler_should_do_transport_work);
216         finished = true;
217
218         if (post_transport_work & PostTransportCurveRealloc) {
219                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
220                         (*i)->curve_reallocate();
221                 }
222         }
223
224         if (post_transport_work & PostTransportInputChange) {
225                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
226                         (*i)->non_realtime_input_change ();
227                 }
228         }
229
230         if (post_transport_work & PostTransportSpeed) {
231                 non_realtime_set_speed ();
232         }
233
234         if (post_transport_work & PostTransportReverse) {
235                 
236                 clear_clicks();
237                 cumulative_rf_motion = 0;
238                 reset_rf_scale (0);
239
240                 /* don't seek if locate will take care of that in non_realtime_stop() */
241
242                 if (!(post_transport_work & PostTransportLocate)) {
243                         
244                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
245                                 if (!(*i)->hidden()) {
246                                         if ((*i)->speed() != 1.0f || (*i)->speed() != -1.0f) {
247                                                 (*i)->seek ((nframes_t) (_transport_frame * (double) (*i)->speed()));
248                                         }
249                                         else {
250                                                 (*i)->seek (_transport_frame);
251                                         }
252                                 }
253                                 if (on_entry != g_atomic_int_get (&butler_should_do_transport_work)) {
254                                         /* new request, stop seeking, and start again */
255                                         g_atomic_int_dec_and_test (&butler_should_do_transport_work);
256                                         goto restart;
257                                 }
258                         }
259                 }
260         }
261
262         if (post_transport_work & (PostTransportStop|PostTransportLocate)) {
263                 non_realtime_stop (post_transport_work & PostTransportAbort, on_entry, finished);
264                 if (!finished) {
265                         g_atomic_int_dec_and_test (&butler_should_do_transport_work);
266                         goto restart;
267                 }
268         }
269
270         if (post_transport_work & PostTransportOverWrite) {
271                 non_realtime_overwrite (on_entry, finished);
272                 if (!finished) {
273                         g_atomic_int_dec_and_test (&butler_should_do_transport_work);
274                         goto restart;
275                 }
276         }
277
278         if (post_transport_work & PostTransportAudition) {
279                 non_realtime_set_audition ();
280         }
281         
282         g_atomic_int_dec_and_test (&butler_should_do_transport_work);
283 }
284
285 void
286 Session::non_realtime_set_speed ()
287 {
288         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
289
290         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
291                 (*i)->non_realtime_set_speed ();
292         }
293 }
294
295 void
296 Session::non_realtime_overwrite (int on_entry, bool& finished)
297 {
298         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
299
300         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
301                 if ((*i)->pending_overwrite) {
302                         (*i)->overwrite_existing_buffers ();
303                 }
304                 if (on_entry != g_atomic_int_get (&butler_should_do_transport_work)) {
305                         finished = false;
306                         return;
307                 }
308         }
309 }
310
311 void
312 Session::non_realtime_stop (bool abort, int on_entry, bool& finished)
313 {
314         struct tm* now;
315         time_t     xnow;
316         bool       did_record;
317         bool       saved;
318
319         did_record = false;
320         saved = false;
321
322         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
323         
324         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
325                 if ((*i)->get_captured_frames () != 0) {
326                         did_record = true;
327                         break;
328                 }
329         }
330
331         /* stop and locate are merged here because they share a lot of common stuff */
332         
333         time (&xnow);
334         now = localtime (&xnow);
335
336         if (auditioner) {
337                 auditioner->cancel_audition ();
338         }
339
340         clear_clicks();
341         cumulative_rf_motion = 0;
342         reset_rf_scale (0);
343
344         if (did_record) {
345                 begin_reversible_command ("capture");
346                 
347                 Location* loc = _locations.end_location();
348                 bool change_end = false;
349                 
350                 if (_transport_frame < loc->end()) {
351
352                         /* stopped recording before current end */
353
354                         if (_end_location_is_free) {
355
356                                 /* first capture for this session, move end back to where we are */
357
358                                 change_end = true;
359                         } 
360
361                 } else if (_transport_frame > loc->end()) {
362                         
363                         /* stopped recording after the current end, extend it */
364
365                         change_end = true;
366                 }
367                 
368                 if (change_end) {
369                         XMLNode &before = loc->get_state();
370                         loc->set_end(_transport_frame);
371                         XMLNode &after = loc->get_state();
372                         add_command (new MementoCommand<Location>(*loc, &before, &after));
373                 }
374
375                 _end_location_is_free = false;
376                 _have_captured = true;
377         }
378
379         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
380                 (*i)->transport_stopped (*now, xnow, abort);
381         }
382         
383         boost::shared_ptr<RouteList> r = routes.reader ();
384
385         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
386                 if (!(*i)->hidden()) {
387                         (*i)->set_pending_declick (0);
388                 }
389         }
390         
391         if (did_record) {
392                 commit_reversible_command ();
393         }       
394         
395         if (_engine.running()) {
396                 update_latency_compensation (true, abort);
397         }
398
399         if ((Config->get_slave_source() == None && Config->get_auto_return()) || 
400             (post_transport_work & PostTransportLocate) || 
401             (_requested_return_frame >= 0) ||
402             synced_to_jack()) {
403                 
404                 if (pending_locate_flush) {
405                         flush_all_redirects ();
406                 }
407                 
408                 if (((Config->get_slave_source() == None && Config->get_auto_return()) || 
409                      synced_to_jack() ||
410                      _requested_return_frame >= 0) &&
411                     !(post_transport_work & PostTransportLocate)) {
412
413                         /* no explicit locate queued */
414
415                         bool do_locate = false;
416
417                         if (_requested_return_frame >= 0) {
418
419                                 /* explicit return request pre-queued in event list. overrides everything else */
420                                 
421                                 _transport_frame = _requested_return_frame;
422                                 do_locate = true;
423
424                         } else {
425                                 if (Config->get_auto_return()) {
426
427                                         if (play_loop) {
428
429                                                 /* don't try to handle loop play when synced to JACK */
430
431                                                 if (!synced_to_jack()) {
432
433                                                         Location *location = _locations.auto_loop_location();
434                                                         
435                                                         if (location != 0) {
436                                                                 _transport_frame = location->start();
437                                                         } else {
438                                                                 _transport_frame = _last_roll_location;
439                                                         }
440                                                         do_locate = true;
441                                                 }
442
443                                         } else if (_play_range) {
444
445                                                 /* return to start of range */
446
447                                                 if (!current_audio_range.empty()) {
448                                                         _transport_frame = current_audio_range.front().start;
449                                                         do_locate = true;
450                                                 }
451
452                                         } else {
453                                                 
454                                                 /* regular auto-return */
455                                                 
456                                                 _transport_frame = _last_roll_location;
457                                                 do_locate = true;
458                                         }
459                                 } 
460                         }
461
462                         _requested_return_frame = -1;                   
463
464                         if (do_locate) {
465                                 _engine.transport_locate (_transport_frame);
466                         }
467                 } 
468
469         }
470
471         /* do this before seeking, because otherwise the Diskstreams will do the wrong thing in seamless loop mode.
472         */
473
474         if (post_transport_work & PostTransportClearSubstate) {
475                 _play_range = false;
476                 unset_play_loop ();
477         }
478
479         /* this for() block can be put inside the previous if() and has the effect of ... ??? what */
480
481         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
482                 if (!(*i)->hidden()) {
483                         if ((*i)->speed() != 1.0f || (*i)->speed() != -1.0f) {
484                                 (*i)->seek ((nframes_t) (_transport_frame * (double) (*i)->speed()));
485                         }
486                         else {
487                                 (*i)->seek (_transport_frame);
488                         }
489                 }
490                 if (on_entry != g_atomic_int_get (&butler_should_do_transport_work)) {
491                         finished = false;
492                         /* we will be back */
493                         return;
494                 }
495         }
496
497         have_looped = false; 
498
499         send_full_time_code ();
500         deliver_mmc (MIDI::MachineControl::cmdStop, 0);
501         deliver_mmc (MIDI::MachineControl::cmdLocate, _transport_frame);
502
503         if (did_record) {
504
505                 /* XXX its a little odd that we're doing this here
506                    when realtime_stop(), which has already executed,
507                    will have done this.
508                    JLC - so let's not because it seems unnecessary and breaks loop record
509                 */
510 #if 0
511                 if (!Config->get_latched_record_enable()) {
512                         g_atomic_int_set (&_record_status, Disabled);
513                 } else {
514                         g_atomic_int_set (&_record_status, Enabled);
515                 }
516                 RecordStateChanged (); /* emit signal */
517 #endif
518         }
519         
520         if ((post_transport_work & PostTransportLocate) && get_record_enabled()) {
521                 /* capture start has been changed, so save pending state */
522                 save_state ("", true);
523                 saved = true;
524         }
525
526         /* always try to get rid of this */
527
528         remove_pending_capture_state ();
529         
530         /* save the current state of things if appropriate */
531
532         if (did_record && !saved) {
533                 save_state (_current_snapshot_name);
534         }
535
536         if (post_transport_work & PostTransportDuration) {
537                 DurationChanged (); /* EMIT SIGNAL */
538         }
539
540         nframes_t tf = _transport_frame;
541
542         PositionChanged (tf); /* EMIT SIGNAL */
543         TransportStateChange (); /* EMIT SIGNAL */
544
545         /* and start it up again if relevant */
546
547         if ((post_transport_work & PostTransportLocate) && Config->get_slave_source() == None && pending_locate_roll) {
548                 request_transport_speed (1.0);
549                 pending_locate_roll = false;
550         }
551 }
552
553 void
554 Session::check_declick_out ()
555 {
556         bool locate_required = transport_sub_state & PendingLocate;
557
558         /* this is called after a process() iteration. if PendingDeclickOut was set,
559            it means that we were waiting to declick the output (which has just been
560            done) before doing something else. this is where we do that "something else".
561            
562            note: called from the audio thread.
563         */
564
565         if (transport_sub_state & PendingDeclickOut) {
566
567                 if (locate_required) {
568                         start_locate (pending_locate_frame, pending_locate_roll, pending_locate_flush);
569                         transport_sub_state &= ~(PendingDeclickOut|PendingLocate);
570                 } else {
571                         stop_transport (pending_abort, pending_clear_substate);
572                         transport_sub_state &= ~(PendingDeclickOut|PendingLocate);
573                 }
574         }
575 }
576
577 void
578 Session::unset_play_loop ()
579 {
580         play_loop = false;
581         clear_events (Event::AutoLoop);
582         
583         // set all diskstreams to NOT use internal looping
584         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
585         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
586                 if (!(*i)->hidden()) {
587                         (*i)->set_loop (0);
588                 }
589         }
590 }
591
592 void
593 Session::set_play_loop (bool yn)
594 {
595         /* Called from event-handling context */
596
597         Location *loc;
598
599         if (yn == play_loop || (actively_recording() && yn) || (loc = _locations.auto_loop_location()) == 0) {
600                 /* nothing to do, or can't change loop status while recording */
601                 return;
602         }
603         
604         set_dirty();
605         
606         if (yn && Config->get_seamless_loop() && synced_to_jack()) {
607                 warning << _("Seamless looping cannot be supported while Ardour is using JACK transport.\n"
608                              "Recommend changing the configured options")
609                         << endmsg;
610                 return;
611         }
612         
613         if (yn) {
614
615                 play_loop = true;
616
617                 if (loc) {
618
619                         set_play_range (false, true);
620
621                         if (Config->get_seamless_loop()) {
622                                 // set all diskstreams to use internal looping
623                                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
624                                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
625                                         if (!(*i)->hidden()) {
626                                                 (*i)->set_loop (loc);
627                                         }
628                                 }
629                         }
630                         else {
631                                 // set all diskstreams to NOT use internal looping
632                                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
633                                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
634                                         if (!(*i)->hidden()) {
635                                                 (*i)->set_loop (0);
636                                         }
637                                 }
638                         }
639                         
640                         /* put the loop event into the event list */
641                         
642                         Event* event = new Event (Event::AutoLoop, Event::Replace, loc->end(), loc->start(), 0.0f);
643                         merge_event (event);
644
645                         /* locate to start of loop and roll. If doing seamless loop, force a 
646                            locate+buffer refill even if we are positioned there already.
647                         */
648
649                         start_locate (loc->start(), true, true, false, Config->get_seamless_loop());
650                 }
651
652         } else {
653
654                 unset_play_loop ();
655         }
656
657         TransportStateChange ();
658 }
659
660 void
661 Session::flush_all_redirects ()
662 {
663         boost::shared_ptr<RouteList> r = routes.reader ();
664
665         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
666                 (*i)->flush_redirects ();
667         }
668 }
669
670 void
671 Session::start_locate (nframes_t target_frame, bool with_roll, bool with_flush, bool with_loop, bool force)
672 {
673         if (synced_to_jack()) {
674
675                 float sp;
676                 nframes_t pos;
677
678                 _slave->speed_and_position (sp, pos);
679
680                 if (target_frame != pos) {
681
682                         /* tell JACK to change transport position, and we will
683                            follow along later in ::follow_slave()
684                         */
685
686                         _engine.transport_locate (target_frame);
687                 }
688
689                 if (sp != 1.0f && with_roll) {
690                         _engine.transport_start ();
691                 }
692
693         } else {
694
695                 locate (target_frame, with_roll, with_flush, with_loop, force);
696         }
697 }
698
699 int
700 Session::micro_locate (nframes_t distance)
701 {
702         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
703         
704         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
705                 if (!(*i)->can_internal_playback_seek (distance)) {
706                         return -1;
707                 }
708         }
709
710         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
711                 (*i)->internal_playback_seek (distance);
712         }
713         
714         _transport_frame += distance;
715         return 0;
716 }
717
718 void
719 Session::locate (nframes_t target_frame, bool with_roll, bool with_flush, bool with_loop, bool force)
720 {
721         if (actively_recording() && !with_loop) {
722                 return;
723         }
724
725         if (!force && _transport_frame == target_frame && !loop_changing && !with_loop) {
726                 if (with_roll) {
727                         set_transport_speed (1.0, false);
728                 }
729                 loop_changing = false;
730                 return;
731         }
732
733         _transport_frame = target_frame;
734
735         if (_transport_speed && (!with_loop || loop_changing)) {
736                 /* schedule a declick. we'll be called again when its done */
737
738                 if (!(transport_sub_state & PendingDeclickOut)) {
739                         transport_sub_state |= (PendingDeclickOut|PendingLocate);
740                         pending_locate_frame = target_frame;
741                         pending_locate_roll = with_roll;
742                         pending_locate_flush = with_flush;
743                         return;
744                 } 
745         }
746
747         /* stop if we are rolling and we're not doing autoplay and we don't plan to roll when done and we not looping while synced to
748            jack
749         */
750
751         if (transport_rolling() && (!auto_play_legal || !Config->get_auto_play()) && !with_roll && !(synced_to_jack() && play_loop)) {
752                 realtime_stop (false, true); // XXX paul - check if the 2nd arg is really correct
753         } 
754
755         if (force || !with_loop || loop_changing) {
756
757                 post_transport_work = PostTransportWork (post_transport_work | PostTransportLocate);
758                 
759                 if (with_roll) {
760                         post_transport_work = PostTransportWork (post_transport_work | PostTransportRoll);
761                 }
762
763                 schedule_butler_transport_work ();
764
765         } else {
766
767                 /* this is functionally what clear_clicks() does but with a tentative lock */
768
769                 Glib::RWLock::WriterLock clickm (click_lock, Glib::TRY_LOCK);
770         
771                 if (clickm.locked()) {
772                         
773                         for (Clicks::iterator i = clicks.begin(); i != clicks.end(); ++i) {
774                                 delete *i;
775                         }
776                 
777                         clicks.clear ();
778                 }
779         }
780
781         if (with_roll) {
782                 /* switch from input if we're going to roll */
783                 if (Config->get_monitoring_model() == HardwareMonitoring) {
784
785                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
786
787                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
788                                 if ((*i)->record_enabled ()) {
789                                         //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
790                                         (*i)->monitor_input (!Config->get_auto_input());
791                                 }
792                         }
793                 }
794         } else {
795                 /* otherwise we're going to stop, so do the opposite */
796                 if (Config->get_monitoring_model() == HardwareMonitoring) {
797                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
798
799                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
800                                 if ((*i)->record_enabled ()) {
801                                         //cerr << "switching to input" << __FILE__ << __LINE__ << endl << endl;
802                                         (*i)->monitor_input (true);
803                                 }
804                         }
805                 }
806         }
807
808         /* cancel looped playback if transport pos outside of loop range */
809         if (play_loop) {
810                 Location* al = _locations.auto_loop_location();
811                 
812                 if (al && (_transport_frame < al->start() || _transport_frame > al->end())) {
813                         // cancel looping directly, this is called from event handling context
814                         set_play_loop (false);
815                 }
816                 else if (al && _transport_frame == al->start()) {
817                         if (with_loop) {
818                                 // this is only necessary for seamless looping
819
820                                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
821                                 
822                                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
823                                         if ((*i)->record_enabled ()) {
824                                                 // tell it we've looped, so it can deal with the record state
825                                                 (*i)->transport_looped(_transport_frame);
826                                         }
827                                 }
828                         }
829                         have_looped = true;
830                         TransportLooped(); // EMIT SIGNAL
831                 }
832         }
833         
834         loop_changing = false;
835
836         _send_smpte_update = true;
837 }
838
839 void
840 Session::set_transport_speed (float speed, bool abort, bool clear_state)
841 {
842         if (_transport_speed == speed) {
843                 return;
844         }
845
846         if (speed > 0) {
847                 speed = min (8.0f, speed);
848         } else if (speed < 0) {
849                 speed = max (-8.0f, speed);
850         }
851
852         if (transport_rolling() && speed == 0.0) {
853
854                 if (Config->get_monitoring_model() == HardwareMonitoring)
855                 {
856                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
857
858                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
859                                 if ((*i)->record_enabled ()) {
860                                         //cerr << "switching to input" << __FILE__ << __LINE__ << endl << endl;
861                                         (*i)->monitor_input (true);     
862                                 }
863                         }
864                 }
865
866                 if (synced_to_jack ()) {
867                         if (clear_state) {
868                                 /* do this here because our response to the slave won't 
869                                    take care of it.
870                                 */
871                                 _play_range = false;
872                                 unset_play_loop ();
873                         }
874                         _engine.transport_stop ();
875                 } else {
876                         stop_transport (abort, clear_state);
877                 }
878                 
879         } else if (transport_stopped() && speed == 1.0) {
880
881                 if (!get_record_enabled() && Config->get_stop_at_session_end() && _transport_frame >= current_end_frame()) {
882                         return;
883                 }
884
885                 if (Config->get_monitoring_model() == HardwareMonitoring) {
886
887                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
888
889                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
890                                 if (Config->get_auto_input() && (*i)->record_enabled ()) {
891                                         //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
892                                         (*i)->monitor_input (false);    
893                                 }
894                         }
895                 }
896
897                 if (synced_to_jack()) {
898                         _engine.transport_start ();
899                 } else {
900                         start_transport ();
901                 }
902
903         } else {
904
905                 if (!get_record_enabled() && Config->get_stop_at_session_end() && _transport_frame >= current_end_frame()) {
906                         return;
907                 }
908
909                 if ((synced_to_jack()) && speed != 0.0 && speed != 1.0) {
910                         warning << _("Global varispeed cannot be supported while Ardour is connected to JACK transport control")
911                                 << endmsg;
912                         return;
913                 }
914
915                 if (actively_recording()) {
916                         return;
917                 }
918
919                 if (speed > 0.0f && _transport_frame == current_end_frame()) {
920                         return;
921                 }
922
923                 if (speed < 0.0f && _transport_frame == 0) {
924                         return;
925                 }
926                 
927                 clear_clicks ();
928
929                 /* if we are reversing relative to the current speed, or relative to the speed
930                    before the last stop, then we have to do extra work.
931                 */
932
933                 PostTransportWork todo = PostTransportWork (0);
934
935                 if ((_transport_speed && speed * _transport_speed < 0.0f) || (_last_transport_speed * speed < 0.0f) || (_last_transport_speed == 0.0f && speed < 0.0f)) {
936                         todo = PostTransportWork (todo | PostTransportReverse);
937                         last_stop_frame = _transport_frame;
938                 }
939                 
940                 _last_transport_speed = _transport_speed;
941                 _transport_speed = speed;
942                 
943                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
944                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
945                         if ((*i)->realtime_set_speed ((*i)->speed(), true)) {
946                                 todo = PostTransportWork (todo | PostTransportSpeed);
947                                 break;
948                         }
949                 }
950                 
951                 if (todo) {
952                         post_transport_work = PostTransportWork (post_transport_work | todo);
953                         schedule_butler_transport_work ();
954                 }
955         }
956 }
957
958 void
959 Session::stop_transport (bool abort, bool clear_state)
960 {
961         if (_transport_speed == 0.0f) {
962                 return;
963         }
964         
965         if (actively_recording() && !(transport_sub_state & StopPendingCapture) && 
966             _worst_output_latency > current_block_size) 
967         {
968                 
969                 /* we need to capture the audio that has still not yet been received by the system
970                    at the time the stop is requested, so we have to roll past that time.
971
972                    we want to declick before stopping, so schedule the autostop for one
973                    block before the actual end. we'll declick in the subsequent block,
974                    and then we'll really be stopped.
975                 */
976                 
977                 Event *ev = new Event (Event::StopOnce, Event::Replace, 
978                                        _transport_frame + _worst_output_latency - current_block_size,
979                                        0, 0, abort);
980                 
981                 merge_event (ev);
982                 transport_sub_state |= StopPendingCapture;
983                 pending_abort = abort;
984                 pending_clear_substate = clear_state;
985                 return;
986         } 
987
988         if ((transport_sub_state & PendingDeclickOut) == 0) {
989                 transport_sub_state |= PendingDeclickOut;
990                 /* we'll be called again after the declick */
991                 pending_abort = abort;
992                 pending_clear_substate = clear_state;
993                 return;
994         }
995
996         realtime_stop (abort, clear_state);
997         schedule_butler_transport_work ();
998 }
999
1000 void
1001 Session::start_transport ()
1002 {
1003         _last_roll_location = _transport_frame;
1004         have_looped = false;
1005
1006         /* if record status is Enabled, move it to Recording. if its
1007            already Recording, move it to Disabled. 
1008         */
1009
1010         switch (record_status()) {
1011         case Enabled:
1012                 if (!Config->get_punch_in()) {
1013                         enable_record ();
1014                 }
1015                 break;
1016
1017         case Recording:
1018                 if (!play_loop) {
1019                         disable_record (false);
1020                 }
1021                 break;
1022
1023         default:
1024                 break;
1025         }
1026
1027         transport_sub_state |= PendingDeclickIn;
1028         _transport_speed = 1.0;
1029         
1030         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1031         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1032                 (*i)->realtime_set_speed ((*i)->speed(), true);
1033         }
1034
1035         send_mmc_in_another_thread (MIDI::MachineControl::cmdDeferredPlay, 0);
1036         
1037         TransportStateChange (); /* EMIT SIGNAL */
1038 }
1039
1040 void
1041 Session::post_transport ()
1042 {
1043         if (post_transport_work & PostTransportAudition) {
1044                 if (auditioner && auditioner->active()) {
1045                         process_function = &Session::process_audition;
1046                 } else {
1047                         process_function = &Session::process_with_events;
1048                 }
1049         }
1050
1051         if (post_transport_work & PostTransportStop) {
1052
1053                 transport_sub_state = 0;
1054         }
1055
1056         if (post_transport_work & PostTransportLocate) {
1057
1058                 if (((Config->get_slave_source() == None && (auto_play_legal && Config->get_auto_play())) && !_exporting) || (post_transport_work & PostTransportRoll)) {
1059                         start_transport ();
1060                         
1061                 } else {
1062                         transport_sub_state = 0;
1063                 }
1064         }
1065
1066         set_next_event ();
1067
1068         post_transport_work = PostTransportWork (0);
1069 }
1070
1071 void
1072 Session::reset_rf_scale (nframes_t motion)
1073 {
1074         cumulative_rf_motion += motion;
1075
1076         if (cumulative_rf_motion < 4 * _current_frame_rate) {
1077                 rf_scale = 1;
1078         } else if (cumulative_rf_motion < 8 * _current_frame_rate) {
1079                 rf_scale = 4;
1080         } else if (cumulative_rf_motion < 16 * _current_frame_rate) {
1081                 rf_scale = 10;
1082         } else {
1083                 rf_scale = 100;
1084         }
1085
1086         if (motion != 0) {
1087                 set_dirty();
1088         }
1089 }
1090
1091 void
1092 Session::set_slave_source (SlaveSource src, bool stop_the_transport)
1093 {
1094         bool reverse = false;
1095         bool non_rt_required = false;
1096
1097         if (_transport_speed) {
1098                 error << _("please stop the transport before adjusting slave settings") << endmsg;
1099                 return;
1100         }
1101
1102 //      if (src == JACK && Config->get_jack_time_master()) {
1103 //              return;
1104 //      }
1105         
1106         if (_slave) {
1107                 delete _slave;
1108                 _slave = 0;
1109         }
1110
1111         if (_transport_speed < 0.0) {
1112                 reverse = true;
1113         }
1114
1115         switch (src) {
1116         case None:
1117                 if (stop_the_transport) {
1118                         stop_transport ();
1119                 }
1120                 break;
1121                 
1122         case MTC:
1123                 if (_mtc_port) {
1124                         try {
1125                                 _slave = new MTC_Slave (*this, *_mtc_port);
1126                         }
1127
1128                         catch (failed_constructor& err) {
1129                                 return;
1130                         }
1131
1132                 } else {
1133                         error << _("No MTC port defined: MTC slaving is impossible.") << endmsg;
1134                         return;
1135                 }
1136                 _desired_transport_speed = _transport_speed;
1137                 break;
1138                 
1139         case JACK:
1140                 _slave = new JACK_Slave (_engine.jack());
1141                 _desired_transport_speed = _transport_speed;
1142                 break;
1143         };
1144
1145         Config->set_slave_source (src);
1146         
1147         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1148         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1149                 if (!(*i)->hidden()) {
1150                         if ((*i)->realtime_set_speed ((*i)->speed(), true)) {
1151                                 non_rt_required = true;
1152                         }
1153                         (*i)->set_slaved (_slave);
1154                 }
1155         }
1156
1157         if (reverse) {
1158                 reverse_diskstream_buffers ();
1159         }
1160
1161         if (non_rt_required) {
1162                 post_transport_work = PostTransportWork (post_transport_work | PostTransportSpeed);
1163                 schedule_butler_transport_work ();
1164         }
1165
1166         set_dirty();
1167 }
1168
1169 void
1170 Session::reverse_diskstream_buffers ()
1171 {
1172         post_transport_work = PostTransportWork (post_transport_work | PostTransportReverse);
1173         schedule_butler_transport_work ();
1174 }
1175
1176 void
1177 Session::set_diskstream_speed (Diskstream* stream, float speed)
1178 {
1179         if (stream->realtime_set_speed (speed, false)) {
1180                 post_transport_work = PostTransportWork (post_transport_work | PostTransportSpeed);
1181                 schedule_butler_transport_work ();
1182                 set_dirty ();
1183         }
1184 }
1185
1186 void
1187 Session::set_audio_range (list<AudioRange>& range)
1188 {
1189         Event *ev = new Event (Event::SetAudioRange, Event::Add, Event::Immediate, 0, 0.0f);
1190         ev->audio_range = range;
1191         queue_event (ev);
1192 }
1193
1194 void
1195 Session::set_play_range (bool yn, bool leave_rolling)
1196 {
1197         /* Called from event-processing context */
1198
1199         if (yn) {
1200                 /* cancel loop play */
1201                 unset_play_loop ();
1202         }
1203
1204         _play_range = yn;
1205
1206         setup_auto_play ();
1207         
1208         if (!_play_range && !leave_rolling) {
1209                 /* stop transport */
1210                 Event* ev = new Event (Event::SetTransportSpeed, Event::Add, Event::Immediate, 0, 0.0f, false);
1211                 merge_event (ev);
1212         }
1213
1214         TransportStateChange ();
1215 }
1216
1217 void
1218 Session::request_bounded_roll (nframes_t start, nframes_t end)
1219 {
1220         AudioRange ar (start, end, 0);
1221         list<AudioRange> lar;
1222         lar.push_back (ar);
1223         set_audio_range (lar);
1224         request_play_range (true, true);
1225 }
1226
1227 void
1228 Session::setup_auto_play ()
1229 {
1230         /* Called from event-processing context */
1231
1232         Event* ev;
1233         
1234         _clear_event_type (Event::RangeStop);
1235         _clear_event_type (Event::RangeLocate);
1236
1237         if (!_play_range) {
1238                 return;
1239         }
1240
1241         list<AudioRange>::size_type sz = current_audio_range.size();
1242         
1243         if (sz > 1) {
1244                 
1245                 list<AudioRange>::iterator i = current_audio_range.begin(); 
1246                 list<AudioRange>::iterator next;
1247                 
1248                 while (i != current_audio_range.end()) {
1249                         
1250                         next = i;
1251                         ++next;
1252                         
1253                         /* locating/stopping is subject to delays for declicking.
1254                          */
1255                         
1256                         nframes_t requested_frame = (*i).end;
1257                         
1258                         if (requested_frame > current_block_size) {
1259                                 requested_frame -= current_block_size;
1260                         } else {
1261                                 requested_frame = 0;
1262                         }
1263                         
1264                         if (next == current_audio_range.end()) {
1265                                 ev = new Event (Event::RangeStop, Event::Add, requested_frame, 0, 0.0f);
1266                         } else {
1267                                 ev = new Event (Event::RangeLocate, Event::Add, requested_frame, (*next).start, 0.0f);
1268                         }
1269                         
1270                         merge_event (ev);
1271                         
1272                         i = next;
1273                 }
1274                 
1275         } else if (sz == 1) {
1276
1277                 ev = new Event (Event::RangeStop, Event::Add, current_audio_range.front().end, 0, 0.0f);
1278                 merge_event (ev);
1279                 
1280         } 
1281
1282         /* now start rolling at the right place */
1283
1284         ev = new Event (Event::LocateRoll, Event::Add, Event::Immediate, current_audio_range.front().start, 0.0f, false);
1285         merge_event (ev);
1286 }
1287
1288 void
1289 Session::request_roll_at_and_return (nframes_t start, nframes_t return_to)
1290 {
1291         Event *ev = new Event (Event::LocateRollLocate, Event::Add, Event::Immediate, return_to, 1.0);
1292         ev->target2_frame = start;
1293         queue_event (ev);
1294 }
1295
1296 void
1297 Session::engine_halted ()
1298 {
1299         bool ignored;
1300
1301         /* there will be no more calls to process(), so
1302            we'd better clean up for ourselves, right now.
1303
1304            but first, make sure the butler is out of 
1305            the picture.
1306         */
1307
1308         g_atomic_int_set (&butler_should_do_transport_work, 0);
1309         post_transport_work = PostTransportWork (0);
1310         stop_butler ();
1311
1312         realtime_stop (false, true);
1313         non_realtime_stop (false, 0, ignored);
1314         transport_sub_state = 0;
1315
1316         if (synced_to_jack()) {
1317                 /* transport is already stopped, hence the second argument */
1318                 set_slave_source (None, false);
1319         }
1320
1321         TransportStateChange (); /* EMIT SIGNAL */
1322 }
1323
1324
1325 void
1326 Session::xrun_recovery ()
1327 {
1328         Xrun (transport_frame()); //EMIT SIGNAL
1329
1330         if (Config->get_stop_recording_on_xrun() && actively_recording()) {
1331
1332                 /* it didn't actually halt, but we need
1333                    to handle things in the same way.
1334                 */
1335
1336                 engine_halted();
1337         } 
1338 }
1339
1340 void
1341 Session::update_latency_compensation (bool with_stop, bool abort)
1342 {
1343         bool update_jack = false;
1344
1345         if (_state_of_the_state & Deletion) {
1346                 return;
1347         }
1348
1349         _worst_track_latency = 0;
1350
1351 #undef DEBUG_LATENCY
1352 #ifdef DEBUG_LATENCY
1353         cerr << "\n---------------------------------\nUPDATE LATENCY\n";
1354 #endif
1355
1356         boost::shared_ptr<RouteList> r = routes.reader ();
1357
1358         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1359                 if (with_stop) {
1360                         (*i)->handle_transport_stopped (abort, (post_transport_work & PostTransportLocate), 
1361                                                         (!(post_transport_work & PostTransportLocate) || pending_locate_flush));
1362                 }
1363
1364                 nframes_t old_latency = (*i)->signal_latency ();
1365                 nframes_t track_latency = (*i)->update_total_latency ();
1366
1367                 if (old_latency != track_latency) {
1368                         update_jack = true;
1369                 }
1370                 
1371                 if (!(*i)->hidden() && ((*i)->active())) {
1372                         _worst_track_latency = max (_worst_track_latency, track_latency);
1373                 }
1374         }
1375
1376 #ifdef DEBUG_LATENCY
1377         cerr << "\tworst was " << _worst_track_latency << endl;
1378 #endif
1379
1380         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1381                 (*i)->set_latency_delay (_worst_track_latency);
1382         }
1383
1384         /* tell JACK to play catch up */
1385
1386         if (update_jack) {
1387                 _engine.update_total_latencies ();
1388         }
1389
1390         set_worst_io_latencies ();
1391
1392         /* reflect any changes in latencies into capture offsets
1393         */
1394         
1395         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1396
1397         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1398                 (*i)->set_capture_offset ();
1399         }
1400 }
1401
1402 void
1403 Session::update_latency_compensation_proxy (void* ignored)
1404 {
1405         update_latency_compensation (false, false);
1406 }
1407
1408 void
1409 Session::allow_auto_play (bool yn)
1410 {
1411         auto_play_legal = yn;
1412 }
1413
1414 void
1415 Session::reset_jack_connection (jack_client_t* jack)
1416 {
1417         JACK_Slave* js;
1418
1419         if (_slave && ((js = dynamic_cast<JACK_Slave*> (_slave)) != 0)) {
1420                 js->reset_client (jack);
1421         }
1422 }
1423
1424 bool
1425 Session::maybe_stop (nframes_t limit)
1426 {
1427         if ((_transport_speed > 0.0f && _transport_frame >= limit) || (_transport_speed < 0.0f && _transport_frame == 0)) {
1428                 if (synced_to_jack () && Config->get_jack_time_master ()) {
1429                         _engine.transport_stop ();
1430                 } else if (!synced_to_jack ()) {
1431                         stop_transport ();
1432                 }
1433                 return true;
1434         }
1435         return false;
1436 }