Clarify stop-at-session-end behaviour; should fix #4033.
[ardour.git] / libs / ardour / session_process.cc
1 /*
2     Copyright (C) 1999-2002 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 <algorithm>
23 #include <unistd.h>
24
25 #include "pbd/error.h"
26 #include "pbd/enumwriter.h"
27
28 #include <glibmm/thread.h>
29
30 #include "ardour/ardour.h"
31 #include "ardour/audioengine.h"
32 #include "ardour/auditioner.h"
33 #include "ardour/butler.h"
34 #include "ardour/debug.h"
35 #include "ardour/process_thread.h"
36 #include "ardour/session.h"
37 #include "ardour/slave.h"
38 #include "ardour/timestamps.h"
39 #include "ardour/graph.h"
40 #include "ardour/audio_port.h"
41
42 #include "midi++/manager.h"
43 #include "midi++/mmc.h"
44
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48 using namespace PBD;
49 using namespace std;
50
51 /** Called by the audio engine when there is work to be done with JACK.
52  * @param nframes Number of frames to process.
53  */
54
55 void
56 Session::process (pframes_t nframes)
57 {
58         MIDI::Manager::instance()->cycle_start(nframes);
59
60         _silent = false;
61
62         if (processing_blocked()) {
63                 _silent = true;
64                 return;
65         }
66
67         if (non_realtime_work_pending()) {
68                 if (!_butler->transport_work_requested ()) {
69                         post_transport ();
70                 }
71         }
72
73         _engine.main_thread()->get_buffers ();
74
75         (this->*process_function) (nframes);
76
77         _engine.main_thread()->drop_buffers ();
78
79         // the ticker is for sending time information like MidiClock
80         framepos_t transport_frames = transport_frame();
81         Timecode::BBT_Time transport_bbt;
82         bbt_time(transport_frames, transport_bbt);
83         Timecode::Time transport_timecode;
84         timecode_time(transport_frames, transport_timecode);
85         tick (transport_frames, transport_bbt, transport_timecode); /* EMIT SIGNAL */
86
87         SendFeedback (); /* EMIT SIGNAL */
88
89         MIDI::Manager::instance()->cycle_end();
90 }
91
92 int
93 Session::fail_roll (pframes_t nframes)
94 {
95         return no_roll (nframes);
96 }
97
98 int
99 Session::no_roll (pframes_t nframes)
100 {
101         framepos_t end_frame = _transport_frame + nframes; // FIXME: varispeed + no_roll ??
102         int ret = 0;
103         bool declick = get_transport_declick_required();
104         boost::shared_ptr<RouteList> r = routes.reader ();
105
106         if (_click_io) {
107                 _click_io->silence (nframes);
108         }
109
110         if (_process_graph->threads_in_use() > 0) {
111                 DEBUG_TRACE(DEBUG::ProcessThreads,"calling graph/no-roll\n");
112                 _process_graph->routes_no_roll( nframes, _transport_frame, end_frame, non_realtime_work_pending(), declick);
113         } else {
114                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
115
116                         if ((*i)->is_hidden()) {
117                                 continue;
118                         }
119
120                         (*i)->set_pending_declick (declick);
121
122                         if ((*i)->no_roll (nframes, _transport_frame, end_frame, non_realtime_work_pending())) {
123                                 error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
124                                 ret = -1;
125                                 break;
126                         }
127                 }
128         }
129
130         return ret;
131 }
132
133 int
134 Session::process_routes (pframes_t nframes, bool& need_butler)
135 {
136         int  declick = get_transport_declick_required();
137         boost::shared_ptr<RouteList> r = routes.reader ();
138
139         if (transport_sub_state & StopPendingCapture) {
140                 /* force a declick out */
141                 declick = -1;
142         }
143
144         const framepos_t start_frame = _transport_frame;
145         const framepos_t end_frame = _transport_frame + floor (nframes * _transport_speed);
146
147         /* XXX this is hack to force use of the graph even if we are only
148            using 1 thread. its needed because otherwise when we remove
149            tracks, the graph never gets updated.
150         */
151         if (1 || _process_graph->threads_in_use() > 0) {
152                 DEBUG_TRACE(DEBUG::ProcessThreads,"calling graph/process-routes\n");
153                 _process_graph->process_routes (nframes, start_frame, end_frame, declick, need_butler);
154         } else {
155
156                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
157
158                         int ret;
159
160                         if ((*i)->is_hidden()) {
161                                 continue;
162                         }
163
164                         (*i)->set_pending_declick (declick);
165
166                         if ((ret = (*i)->roll (nframes, start_frame, end_frame, declick, need_butler)) < 0) {
167                                 stop_transport ();
168                                 return -1;
169                         }
170                 }
171         }
172
173         return 0;
174 }
175
176 int
177 Session::silent_process_routes (pframes_t nframes, bool& need_butler)
178 {
179         boost::shared_ptr<RouteList> r = routes.reader ();
180
181         const framepos_t start_frame = _transport_frame;
182         const framepos_t end_frame = _transport_frame + lrintf(nframes * _transport_speed);
183
184         /* XXX this is hack to force use of the graph even if we are only
185            using 1 thread. its needed because otherwise when we remove
186            tracks, the graph never gets updated.
187         */
188         if (1 || _process_graph->threads_in_use() > 0) {
189                 _process_graph->silent_process_routes (nframes, start_frame, end_frame, need_butler);
190         } else {
191                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
192
193                         int ret;
194
195                         if ((*i)->is_hidden()) {
196                                 continue;
197                         }
198
199                         if ((ret = (*i)->silent_roll (nframes, start_frame, end_frame, need_butler)) < 0) {
200                                 stop_transport ();
201                                 return -1;
202                         }
203                 }
204         }
205
206         return 0;
207 }
208
209 void
210 Session::get_track_statistics ()
211 {
212         float pworst = 1.0f;
213         float cworst = 1.0f;
214
215         boost::shared_ptr<RouteList> rl = routes.reader();
216         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
217
218                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
219
220                 if (!tr || tr->hidden()) {
221                         continue;
222                 }
223
224                 pworst = min (pworst, tr->playback_buffer_load());
225                 cworst = min (cworst, tr->capture_buffer_load());
226         }
227
228         g_atomic_int_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
229         g_atomic_int_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
230
231         if (actively_recording()) {
232                 set_dirty();
233         }
234 }
235
236 /** Process callback used when the auditioner is not active */
237 void
238 Session::process_with_events (pframes_t nframes)
239 {
240         SessionEvent*  ev;
241         pframes_t      this_nframes;
242         framepos_t     end_frame;
243         bool           session_needs_butler = false;
244         framecnt_t     frames_moved;
245
246         /* make sure the auditioner is silent */
247
248         if (auditioner) {
249                 auditioner->silence (nframes);
250         }
251
252         /* handle any pending events */
253
254         while (pending_events.read (&ev, 1) == 1) {
255                 merge_event (ev);
256         }
257
258         /* if we are not in the middle of a state change,
259            and there are immediate events queued up,
260            process them.
261         */
262
263         while (!non_realtime_work_pending() && !immediate_events.empty()) {
264                 SessionEvent *ev = immediate_events.front ();
265                 immediate_events.pop_front ();
266                 process_event (ev);
267         }
268
269         /* Decide on what to do with quarter-frame MTC during this cycle */
270
271         bool const was_sending_qf_mtc = _send_qf_mtc;
272         double const tolerance = Config->get_mtc_qf_speed_tolerance() / 100.0;
273
274         if (_transport_speed != 0) {
275                 _send_qf_mtc = (
276                         Config->get_send_mtc () &&
277                         _transport_speed >= (1 - tolerance) &&
278                         _transport_speed <= (1 + tolerance)
279                         );
280
281                 if (_send_qf_mtc && !was_sending_qf_mtc) {
282                         /* we will re-start quarter-frame MTC this cycle, so send a full update to set things up */
283                         _send_timecode_update = true;
284                 }
285
286                 if (Config->get_send_mtc() && !_send_qf_mtc && _pframes_since_last_mtc > (frame_rate () / 4)) {
287                         /* we're sending MTC, but we're not sending QF MTC at the moment, and it's been
288                            a quarter of a second since we sent anything at all, so send a full MTC update
289                            this cycle.
290                         */
291                         _send_timecode_update = true;
292                 }
293
294                 _pframes_since_last_mtc += nframes;
295         }
296
297         /* Events caused a transport change (or we re-started sending
298          * MTC), so send an MTC Full Frame (Timecode) message.  This
299          * is sent whether rolling or not, to give slaves an idea of
300          * ardour time on locates (and allow slow slaves to position
301          * and prepare for rolling)
302          */
303         if (_send_timecode_update) {
304                 send_full_time_code (_transport_frame);
305         }
306
307         if (!process_can_proceed()) {
308                 _silent = true;
309                 return;
310         }
311
312         if (events.empty() || next_event == events.end()) {
313                 process_without_events (nframes);
314                 return;
315         }
316
317         if (_transport_speed == 1.0) {
318                 frames_moved = (framecnt_t) nframes;
319         } else {
320                 interpolation.set_target_speed (fabs(_target_transport_speed));
321                 interpolation.set_speed (fabs(_transport_speed));
322                 frames_moved = (framecnt_t) interpolation.interpolate (0, nframes, 0, 0);
323         }
324
325         end_frame = _transport_frame + frames_moved;
326
327         {
328                 SessionEvent* this_event;
329                 Events::iterator the_next_one;
330
331                 if (!process_can_proceed()) {
332                         _silent = true;
333                         return;
334                 }
335
336                 if (!_exporting && _slave) {
337                         if (!follow_slave (nframes)) {
338                                 return;
339                         }
340                 }
341
342                 if (_transport_speed == 0) {
343                         no_roll (nframes);
344                         return;
345                 }
346
347                 if (!_exporting && !timecode_transmission_suspended()) {
348                         send_midi_time_code_for_cycle (_transport_frame, end_frame, nframes);
349                 }
350
351                 framepos_t stop_limit = compute_stop_limit ();
352
353                 if (maybe_stop (stop_limit)) {
354                         no_roll (nframes);
355                         return;
356                 }
357
358                 this_event = *next_event;
359                 the_next_one = next_event;
360                 ++the_next_one;
361
362                 /* yes folks, here it is, the actual loop where we really truly
363                    process some audio
364                 */
365
366                 while (nframes) {
367
368                         this_nframes = nframes; /* real (jack) time relative */
369                         frames_moved = (framecnt_t) floor (_transport_speed * nframes); /* transport relative */
370
371                         /* running an event, position transport precisely to its time */
372                         if (this_event && this_event->action_frame <= end_frame && this_event->action_frame >= _transport_frame) {
373                                 /* this isn't quite right for reverse play */
374                                 frames_moved = (framecnt_t) (this_event->action_frame - _transport_frame);
375                                 this_nframes = abs (floor(frames_moved / _transport_speed));
376                         }
377
378                         if (this_nframes) {
379
380                                 click (_transport_frame, this_nframes);
381
382                                 if (process_routes (this_nframes, session_needs_butler)) {
383                                         fail_roll (nframes);
384                                         return;
385                                 }
386
387                                 get_track_statistics ();
388
389                                 nframes -= this_nframes;
390
391                                 if (frames_moved < 0) {
392                                         decrement_transport_position (-frames_moved);
393                                 } else {
394                                         increment_transport_position (frames_moved);
395                                 }
396
397                                 maybe_stop (stop_limit);
398                                 check_declick_out ();
399                         }
400
401                         _engine.split_cycle (this_nframes);
402
403                         /* now handle this event and all others scheduled for the same time */
404
405                         while (this_event && this_event->action_frame == _transport_frame) {
406                                 process_event (this_event);
407
408                                 if (the_next_one == events.end()) {
409                                         this_event = 0;
410                                 } else {
411                                         this_event = *the_next_one;
412                                         ++the_next_one;
413                                 }
414                         }
415
416                         /* if an event left our state changing, do the right thing */
417
418                         if (nframes && non_realtime_work_pending()) {
419                                 no_roll (nframes);
420                                 break;
421                         }
422
423                         /* this is necessary to handle the case of seamless looping */
424                         end_frame = _transport_frame + floor (nframes * _transport_speed);
425                 }
426
427                 set_next_event ();
428
429         } /* implicit release of route lock */
430
431         if (session_needs_butler) {
432                 _butler->summon ();
433         }
434 }
435
436 void
437 Session::reset_slave_state ()
438 {
439         average_slave_delta = 1800;
440         delta_accumulator_cnt = 0;
441         have_first_delta_accumulator = false;
442         _slave_state = Stopped;
443 }
444
445 bool
446 Session::transport_locked () const
447 {
448         Slave* sl = _slave;
449
450         if (!locate_pending() && (!config.get_external_sync() || (sl && sl->ok() && sl->locked()))) {
451                 return true;
452         }
453
454         return false;
455 }
456
457 bool
458 Session::follow_slave (pframes_t nframes)
459 {
460         double slave_speed;
461         framepos_t slave_transport_frame;
462         framecnt_t this_delta;
463         int dir;
464
465         if (!_slave->ok()) {
466                 stop_transport ();
467                 config.set_external_sync (false);
468                 goto noroll;
469         }
470
471         _slave->speed_and_position (slave_speed, slave_transport_frame);
472
473         DEBUG_TRACE (DEBUG::Slave, string_compose ("Slave position %1 speed %2\n", slave_transport_frame, slave_speed));
474
475         if (!_slave->locked()) {
476                 DEBUG_TRACE (DEBUG::Slave, "slave not locked\n");
477                 goto noroll;
478         }
479
480         if (slave_transport_frame > _transport_frame) {
481                 this_delta = slave_transport_frame - _transport_frame;
482                 dir = 1;
483         } else {
484                 this_delta = _transport_frame - slave_transport_frame;
485                 dir = -1;
486         }
487
488         if (_slave->starting()) {
489                 slave_speed = 0.0f;
490         }
491
492         if (_slave->is_always_synced() || config.get_timecode_source_is_synced()) {
493
494                 /* if the TC source is synced, then we assume that its
495                    speed is binary: 0.0 or 1.0
496                 */
497
498                 if (slave_speed != 0.0f) {
499                         slave_speed = 1.0f;
500                 }
501
502         } else {
503
504                 /* if we are chasing and the average delta between us and the
505                    master gets too big, we want to switch to silent
506                    motion. so keep track of that here.
507                 */
508
509                 if (_slave_state == Running) {
510                         calculate_moving_average_of_slave_delta(dir, this_delta);
511                 }
512         }
513
514         track_slave_state (slave_speed, slave_transport_frame, this_delta);
515
516         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave state %1 @ %2 speed %3 cur delta %4 avg delta %5\n",
517                                                    _slave_state, slave_transport_frame, slave_speed, this_delta, average_slave_delta));
518
519
520         if (_slave_state == Running && !_slave->is_always_synced() && !config.get_timecode_source_is_synced()) {
521
522                 if (_transport_speed != 0.0f) {
523
524                         /*
525                            note that average_dir is +1 or -1
526                         */
527
528                         float delta;
529
530                         if (average_slave_delta == 0) {
531                                 delta = this_delta;
532                                 delta *= dir;
533                         } else {
534                                 delta = average_slave_delta;
535                                 delta *= average_dir;
536                         }
537
538 #ifndef NDEBUG
539                         if (slave_speed != 0.0) {
540                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("delta = %1 speed = %2 ts = %3 M@%4 S@%5 avgdelta %6\n",
541                                                                            (int) (dir * this_delta),
542                                                                            slave_speed,
543                                                                            _transport_speed,
544                                                                            _transport_frame,
545                                                                            slave_transport_frame,
546                                                                            average_slave_delta));
547                         }
548 #endif
549
550                         if (_slave->give_slave_full_control_over_transport_speed()) {
551                                 set_transport_speed (slave_speed, false, false);
552                                 //std::cout << "set speed = " << slave_speed << "\n";
553                         } else {
554                                 float adjusted_speed = slave_speed + (1.5 * (delta /  float(_current_frame_rate)));
555                                 request_transport_speed (adjusted_speed);
556                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("adjust using %1 towards %2 ratio %3 current %4 slave @ %5\n",
557                                                                            delta, adjusted_speed, adjusted_speed/slave_speed, _transport_speed,
558                                                                            slave_speed));
559                         }
560
561 #if 1
562                         if ((framecnt_t) abs(average_slave_delta) > _slave->resolution()) {
563                                 cerr << "average slave delta greater than slave resolution (" << _slave->resolution() << "), going to silent motion\n";
564                                 goto silent_motion;
565                         }
566 #endif
567                 }
568         }
569
570
571         if (_slave_state == Running && !non_realtime_work_pending()) {
572                 /* speed is set, we're locked, and good to go */
573                 return true;
574         }
575
576   silent_motion:
577         DEBUG_TRACE (DEBUG::Slave, "silent motion\n")
578         follow_slave_silently (nframes, slave_speed);
579
580   noroll:
581         /* don't move at all */
582         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
583         no_roll (nframes);
584         return false;
585 }
586
587 void
588 Session::calculate_moving_average_of_slave_delta (int dir, framecnt_t this_delta)
589 {
590         if (delta_accumulator_cnt >= delta_accumulator_size) {
591                 have_first_delta_accumulator = true;
592                 delta_accumulator_cnt = 0;
593         }
594
595         if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
596                 delta_accumulator[delta_accumulator_cnt++] = (framecnt_t) dir *  (framecnt_t) this_delta;
597         }
598
599         if (have_first_delta_accumulator) {
600                 average_slave_delta = 0L;
601                 for (int i = 0; i < delta_accumulator_size; ++i) {
602                         average_slave_delta += delta_accumulator[i];
603                 }
604                 average_slave_delta /= (int32_t) delta_accumulator_size;
605                 if (average_slave_delta < 0L) {
606                         average_dir = -1;
607                         average_slave_delta = abs(average_slave_delta);
608                 } else {
609                         average_dir = 1;
610                 }
611         }
612 }
613
614 void
615 Session::track_slave_state (float slave_speed, framepos_t slave_transport_frame, framecnt_t /*this_delta*/)
616 {
617         if (slave_speed != 0.0f) {
618
619                 /* slave is running */
620
621                 switch (_slave_state) {
622                 case Stopped:
623                         if (_slave->requires_seekahead()) {
624                                 slave_wait_end = slave_transport_frame + _slave->seekahead_distance ();
625                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, but running, requires seekahead to %1\n", slave_wait_end));
626                                 /* we can call locate() here because we are in process context */
627                                 locate (slave_wait_end, false, false);
628                                 _slave_state = Waiting;
629
630                         } else {
631
632                                 _slave_state = Running;
633
634                                 Location* al = _locations->auto_loop_location();
635
636                                 if (al && play_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
637                                         // cancel looping
638                                         request_play_loop(false);
639                                 }
640
641                                 if (slave_transport_frame != _transport_frame) {
642                                         locate (slave_transport_frame, false, false);
643                                 }
644                         }
645                         break;
646
647                 case Waiting:
648                 default:
649                         break;
650                 }
651
652                 if (_slave_state == Waiting) {
653
654                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave waiting at %1\n", slave_transport_frame));
655
656                         if (slave_transport_frame >= slave_wait_end) {
657
658                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave start at %1 vs %2\n", slave_transport_frame, _transport_frame));
659
660                                 _slave_state = Running;
661
662                                 /* now perform a "micro-seek" within the disk buffers to realign ourselves
663                                    precisely with the master.
664                                 */
665
666
667                                 bool ok = true;
668                                 framecnt_t frame_delta = slave_transport_frame - _transport_frame;
669
670                                 boost::shared_ptr<RouteList> rl = routes.reader();
671                                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
672                                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
673                                         if (tr && !tr->can_internal_playback_seek (frame_delta)) {
674                                                 ok = false;
675                                                 break;
676                                         }
677                                 }
678
679                                 if (ok) {
680                                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
681                                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
682                                                 if (tr) {
683                                                         tr->internal_playback_seek (frame_delta);
684                                                 }
685                                         }
686                                         _transport_frame += frame_delta;
687
688                                 } else {
689                                         cerr << "cannot micro-seek\n";
690                                         /* XXX what? */
691                                 }
692
693                                 memset (delta_accumulator, 0, sizeof (int32_t) * delta_accumulator_size);
694                                 average_slave_delta = 0L;
695                         }
696                 }
697
698                 if (_slave_state == Running && _transport_speed == 0.0f) {
699                         DEBUG_TRACE (DEBUG::Slave, "slave starts transport\n");
700                         start_transport ();
701                 }
702
703         } else { // slave_speed is 0
704
705                 /* slave has stopped */
706
707                 if (_transport_speed != 0.0f) {
708                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 frame %2 tf %3\n", slave_speed, slave_transport_frame, _transport_frame));
709                         stop_transport ();
710                 }
711
712                 if (slave_transport_frame != _transport_frame) {
713                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, move to %1\n", slave_transport_frame));
714                         force_locate (slave_transport_frame, false);
715                 }
716
717                 _slave_state = Stopped;
718         }
719 }
720
721 void
722 Session::follow_slave_silently (pframes_t nframes, float slave_speed)
723 {
724         if (slave_speed && _transport_speed) {
725
726                 /* something isn't right, but we should move with the master
727                    for now.
728                 */
729
730                 bool need_butler;
731
732                 silent_process_routes (nframes, need_butler);
733
734                 get_track_statistics ();
735
736                 if (need_butler) {
737                         _butler->summon ();
738                 }
739
740                 int32_t frames_moved = (int32_t) floor (_transport_speed * nframes);
741
742                 if (frames_moved < 0) {
743                         decrement_transport_position (-frames_moved);
744                 } else {
745                         increment_transport_position (frames_moved);
746                 }
747
748                 framepos_t const stop_limit = compute_stop_limit ();
749                 maybe_stop (stop_limit);
750         }
751 }
752
753 void
754 Session::process_without_events (pframes_t nframes)
755 {
756         bool session_needs_butler = false;
757         framecnt_t frames_moved;
758
759         if (!process_can_proceed()) {
760                 _silent = true;
761                 return;
762         }
763
764         if (!_exporting && _slave) {
765                 if (!follow_slave (nframes)) {
766                         return;
767                 }
768         }
769
770         if (_transport_speed == 0) {
771                 fail_roll (nframes);
772                 return;
773         }
774
775         if (_transport_speed == 1.0) {
776                 frames_moved = (framecnt_t) nframes;
777         } else {
778                 interpolation.set_target_speed (fabs(_target_transport_speed));
779                 interpolation.set_speed (fabs(_transport_speed));
780                 frames_moved = (framecnt_t) interpolation.interpolate (0, nframes, 0, 0);
781         }
782
783         if (!_exporting && !timecode_transmission_suspended()) {
784                 send_midi_time_code_for_cycle (_transport_frame, _transport_frame + frames_moved, nframes);
785         }
786
787         framepos_t const stop_limit = compute_stop_limit ();
788
789         if (maybe_stop (stop_limit)) {
790                 fail_roll (nframes);
791                 return;
792         }
793
794         if (maybe_sync_start (nframes)) {
795                 return;
796         }
797
798         click (_transport_frame, nframes);
799
800         if (process_routes (nframes, session_needs_butler)) {
801                 fail_roll (nframes);
802                 return;
803         }
804
805         get_track_statistics ();
806
807         /* XXX: I'm not sure whether this is correct, but at least it
808            matches process_with_events, so that this new frames_moved
809            is -ve when transport speed is -ve.  This means that the
810            transport position is updated correctly when we are in
811            reverse.  It seems a bit wrong that we're not using the
812            interpolator to compute this.
813         */
814
815         frames_moved = (framecnt_t) floor (_transport_speed * nframes);
816
817         if (frames_moved < 0) {
818                 decrement_transport_position (-frames_moved);
819         } else {
820                 increment_transport_position (frames_moved);
821         }
822
823         maybe_stop (stop_limit);
824         check_declick_out ();
825
826         if (session_needs_butler) {
827                 _butler->summon ();
828         }
829 }
830
831 /** Process callback used when the auditioner is active.
832  * @param nframes number of frames to process.
833  */
834 void
835 Session::process_audition (pframes_t nframes)
836 {
837         SessionEvent* ev;
838         boost::shared_ptr<RouteList> r = routes.reader ();
839
840         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
841                 if (!(*i)->is_hidden()) {
842                         (*i)->silence (nframes);
843                 }
844         }
845
846         /* run the auditioner, and if it says we need butler service, ask for it */
847
848         if (auditioner->play_audition (nframes) > 0) {
849                 _butler->summon ();
850         }
851
852         /* if using a monitor section, run it because otherwise we don't hear anything */
853
854         if (auditioner->needs_monitor()) {
855                 _monitor_out->passthru (_transport_frame, _transport_frame + nframes, nframes, false);
856         }
857
858         /* handle pending events */
859
860         while (pending_events.read (&ev, 1) == 1) {
861                 merge_event (ev);
862         }
863
864         /* if we are not in the middle of a state change,
865            and there are immediate events queued up,
866            process them.
867         */
868
869         while (!non_realtime_work_pending() && !immediate_events.empty()) {
870                 SessionEvent *ev = immediate_events.front ();
871                 immediate_events.pop_front ();
872                 process_event (ev);
873         }
874
875         if (!auditioner->auditioning()) {
876                 /* auditioner no longer active, so go back to the normal process callback */
877                 process_function = &Session::process_with_events;
878         }
879 }
880
881 bool
882 Session::maybe_sync_start (pframes_t & nframes)
883 {
884         pframes_t sync_offset;
885
886         if (!waiting_for_sync_offset) {
887                 return false;
888         }
889
890         if (_engine.get_sync_offset (sync_offset) && sync_offset < nframes) {
891
892                 /* generate silence up to the sync point, then
893                    adjust nframes + offset to reflect whatever
894                    is left to do.
895                 */
896
897                 no_roll (sync_offset);
898                 nframes -= sync_offset;
899                 Port::increment_global_port_buffer_offset (sync_offset);
900                 waiting_for_sync_offset = false;
901
902                 if (nframes == 0) {
903                         return true; // done, nothing left to process
904                 }
905
906         } else {
907
908                 /* sync offset point is not within this process()
909                    cycle, so just generate silence. and don't bother
910                    with any fancy stuff here, just the minimal silence.
911                 */
912
913                 _silent = true;
914
915                 if (Config->get_locate_while_waiting_for_sync()) {
916                         if (micro_locate (nframes)) {
917                                 /* XXX ERROR !!! XXX */
918                         }
919                 }
920
921                 return true; // done, nothing left to process
922         }
923
924         return false;
925 }
926
927 void
928 Session::queue_event (SessionEvent* ev)
929 {
930         if (_state_of_the_state & Deletion) {
931                 return;
932         } else if (_state_of_the_state & Loading) {
933                 merge_event (ev);
934         } else {
935                 pending_events.write (&ev, 1);
936         }
937 }
938
939 void
940 Session::set_next_event ()
941 {
942         if (events.empty()) {
943                 next_event = events.end();
944                 return;
945         }
946
947         if (next_event == events.end()) {
948                 next_event = events.begin();
949         }
950
951         if ((*next_event)->action_frame > _transport_frame) {
952                 next_event = events.begin();
953         }
954
955         for (; next_event != events.end(); ++next_event) {
956                 if ((*next_event)->action_frame >= _transport_frame) {
957                         break;
958                 }
959         }
960 }
961
962 void
963 Session::process_event (SessionEvent* ev)
964 {
965         bool remove = true;
966         bool del = true;
967
968         /* if we're in the middle of a state change (i.e. waiting
969            for the butler thread to complete the non-realtime
970            part of the change), we'll just have to queue this
971            event for a time when the change is complete.
972         */
973
974         if (non_realtime_work_pending()) {
975
976                 /* except locates, which we have the capability to handle */
977
978                 if (ev->type != SessionEvent::Locate) {
979                         immediate_events.insert (immediate_events.end(), ev);
980                         _remove_event (ev);
981                         return;
982                 }
983         }
984
985         DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Processing event: %1 @ %2\n", enum_2_string (ev->type), _transport_frame));
986
987         switch (ev->type) {
988         case SessionEvent::SetLoop:
989                 set_play_loop (ev->yes_or_no);
990                 break;
991
992         case SessionEvent::AutoLoop:
993                 if (play_loop) {
994                         start_locate (ev->target_frame, true, false, Config->get_seamless_loop());
995                 }
996                 remove = false;
997                 del = false;
998                 break;
999
1000         case SessionEvent::Locate:
1001                 if (ev->yes_or_no) {
1002                         // cerr << "forced locate to " << ev->target_frame << endl;
1003                         locate (ev->target_frame, false, true, false);
1004                 } else {
1005                         // cerr << "soft locate to " << ev->target_frame << endl;
1006                         start_locate (ev->target_frame, false, true, false);
1007                 }
1008                 _send_timecode_update = true;
1009                 break;
1010
1011         case SessionEvent::LocateRoll:
1012                 if (ev->yes_or_no) {
1013                         // cerr << "forced locate to+roll " << ev->target_frame << endl;
1014                         locate (ev->target_frame, true, true, false);
1015                 } else {
1016                         // cerr << "soft locate to+roll " << ev->target_frame << endl;
1017                         start_locate (ev->target_frame, true, true, false);
1018                 }
1019                 _send_timecode_update = true;
1020                 break;
1021
1022         case SessionEvent::LocateRollLocate:
1023                 // locate is handled by ::request_roll_at_and_return()
1024                 _requested_return_frame = ev->target_frame;
1025                 request_locate (ev->target2_frame, true);
1026                 break;
1027
1028
1029         case SessionEvent::SetTransportSpeed:
1030                 set_transport_speed (ev->speed, ev->yes_or_no, ev->second_yes_or_no);
1031                 break;
1032
1033         case SessionEvent::PunchIn:
1034                 // cerr << "PunchIN at " << transport_frame() << endl;
1035                 if (config.get_punch_in() && record_status() == Enabled) {
1036                         enable_record ();
1037                 }
1038                 remove = false;
1039                 del = false;
1040                 break;
1041
1042         case SessionEvent::PunchOut:
1043                 // cerr << "PunchOUT at " << transport_frame() << endl;
1044                 if (config.get_punch_out()) {
1045                         step_back_from_record ();
1046                 }
1047                 remove = false;
1048                 del = false;
1049                 break;
1050
1051         case SessionEvent::StopOnce:
1052                 if (!non_realtime_work_pending()) {
1053                         stop_transport (ev->yes_or_no);
1054                         _clear_event_type (SessionEvent::StopOnce);
1055                 }
1056                 remove = false;
1057                 del = false;
1058                 break;
1059
1060         case SessionEvent::RangeStop:
1061                 if (!non_realtime_work_pending()) {
1062                         stop_transport (ev->yes_or_no);
1063                 }
1064                 remove = false;
1065                 del = false;
1066                 break;
1067
1068         case SessionEvent::RangeLocate:
1069                 start_locate (ev->target_frame, true, true, false);
1070                 remove = false;
1071                 del = false;
1072                 break;
1073
1074         case SessionEvent::Overwrite:
1075                 overwrite_some_buffers (static_cast<Track*>(ev->ptr));
1076                 break;
1077
1078         case SessionEvent::SetTrackSpeed:
1079                 set_track_speed (static_cast<Track*> (ev->ptr), ev->speed);
1080                 break;
1081
1082         case SessionEvent::SetSyncSource:
1083                 use_sync_source (ev->slave);
1084                 break;
1085
1086         case SessionEvent::Audition:
1087                 set_audition (ev->region);
1088                 // drop reference to region
1089                 ev->region.reset ();
1090                 break;
1091
1092         case SessionEvent::InputConfigurationChange:
1093                 add_post_transport_work (PostTransportInputChange);
1094                 _butler->schedule_transport_work ();
1095                 break;
1096
1097         case SessionEvent::SetPlayAudioRange:
1098                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
1099                 break;
1100
1101         case SessionEvent::RealTimeOperation:
1102                 process_rtop (ev);
1103                 del = false; // other side of RT request needs to clean up
1104                 break;
1105
1106         case SessionEvent::AdjustPlaybackBuffering:
1107                 schedule_playback_buffering_adjustment ();
1108                 break;
1109
1110         case SessionEvent::AdjustCaptureBuffering:
1111                 schedule_capture_buffering_adjustment ();
1112                 break;
1113
1114         case SessionEvent::SetTimecodeTransmission:
1115                 g_atomic_int_set (&_suspend_timecode_transmission, ev->yes_or_no ? 0 : 1);
1116                 break;
1117
1118         default:
1119           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
1120                 /*NOTREACHED*/
1121                 break;
1122         };
1123
1124         if (remove) {
1125                 del = del && !_remove_event (ev);
1126         }
1127
1128         if (del) {
1129                 delete ev;
1130         }
1131 }
1132
1133 framepos_t
1134 Session::compute_stop_limit () const
1135 {
1136         if (!Config->get_stop_at_session_end ()) {
1137                 return max_framepos;
1138         }
1139         
1140         bool const punching_in = (config.get_punch_in () && _locations->auto_punch_location());
1141         bool const punching_out = (config.get_punch_out () && _locations->auto_punch_location());
1142
1143         if (actively_recording ()) {
1144                 /* permanently recording */
1145                 return max_framepos;
1146         } else if (punching_in && !punching_out) {
1147                 /* punching in but never out */
1148                 return max_framepos;
1149         } else if (punching_in && punching_out && _locations->auto_punch_location()->end() > current_end_frame()) {
1150                 /* punching in and punching out after session end */
1151                 return max_framepos;
1152         }
1153
1154         return current_end_frame ();
1155 }