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