better, cleaner, more generic version of real-time ping pong, still just for one...
[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/audio_diskstream.h"
32 #include "ardour/audioengine.h"
33 #include "ardour/auditioner.h"
34 #include "ardour/butler.h"
35 #include "ardour/debug.h"
36 #include "ardour/session.h"
37 #include "ardour/slave.h"
38 #include "ardour/timestamps.h"
39
40 #include "midi++/manager.h"
41
42 #include "i18n.h"
43
44 using namespace ARDOUR;
45 using namespace PBD;
46 using namespace std;
47
48 /** Called by the audio engine when there is work to be done with JACK.
49  * @param nframes Number of frames to process.
50  */
51 void
52 Session::process (nframes_t nframes)
53 {
54         // This is no more the appropriate place to call cycle
55         // start. cycle_start needs to be called at the Route::roll()
56         // where the signals which we want to mixdown have been calculated.
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         (this->*process_function) (nframes);
74
75         // the ticker is for sending time information like MidiClock
76         nframes_t transport_frames = transport_frame();
77         BBT_Time  transport_bbt;
78         bbt_time(transport_frames, transport_bbt);
79         Timecode::Time transport_timecode;
80         timecode_time(transport_frames, transport_timecode);
81         tick (transport_frames, transport_bbt, transport_timecode); /* EMIT SIGNAL */
82
83         SendFeedback (); /* EMIT SIGNAL */
84
85         MIDI::Manager::instance()->cycle_end();
86 }
87
88 void
89 Session::prepare_diskstreams ()
90 {
91         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
92         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
93                 (*i)->prepare ();
94         }
95 }
96
97 int
98 Session::fail_roll (nframes_t nframes)
99 {
100         return no_roll (nframes);
101 }
102
103 int
104 Session::no_roll (nframes_t nframes)
105 {
106         nframes_t end_frame = _transport_frame + nframes; // FIXME: varispeed + no_roll ??
107         int ret = 0;
108         bool declick = get_transport_declick_required();
109         boost::shared_ptr<RouteList> r = routes.reader ();
110
111         if (_click_io) {
112                 _click_io->silence (nframes);
113         }
114
115         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
116
117                 if ((*i)->is_hidden()) {
118                         continue;
119                 }
120
121                 (*i)->set_pending_declick (declick);
122
123                 if ((*i)->no_roll (nframes, _transport_frame, end_frame, non_realtime_work_pending(),
124                                    actively_recording(), declick)) {
125                         error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
126                         ret = -1;
127                         break;
128                 }
129         }
130
131         return ret;
132 }
133
134 int
135 Session::process_routes (nframes_t nframes)
136 {
137         bool record_active;
138         int  declick = get_transport_declick_required();
139         bool rec_monitors = get_rec_monitors_input();
140         boost::shared_ptr<RouteList> r = routes.reader ();
141
142         if (transport_sub_state & StopPendingCapture) {
143                 /* force a declick out */
144                 declick = -1;
145         }
146
147         record_active = actively_recording(); // || (get_record_enabled() && get_punch_in());
148
149         const nframes_t start_frame = _transport_frame;
150         const nframes_t end_frame = _transport_frame + (nframes_t)floor(nframes * _transport_speed);
151
152         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
153
154                 int ret;
155
156                 if ((*i)->is_hidden()) {
157                         continue;
158                 }
159
160                 (*i)->set_pending_declick (declick);
161
162                 if ((ret = (*i)->roll (nframes, start_frame, end_frame, declick, record_active, rec_monitors)) < 0) {
163
164                         /* we have to do this here. Route::roll() for an AudioTrack will have called AudioDiskstream::process(),
165                            and the DS will expect AudioDiskstream::commit() to be called. but we're aborting from that
166                            call path, so make sure we release any outstanding locks here before we return failure.
167                         */
168
169                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
170                         for (DiskstreamList::iterator ids = dsl->begin(); ids != dsl->end(); ++ids) {
171                                 (*ids)->recover ();
172                         }
173
174                         stop_transport ();
175                         return -1;
176                 }
177         }
178
179         return 0;
180 }
181
182 int
183 Session::silent_process_routes (nframes_t nframes)
184 {
185         bool record_active = actively_recording();
186         int  declick = get_transport_declick_required();
187         bool rec_monitors = get_rec_monitors_input();
188         boost::shared_ptr<RouteList> r = routes.reader ();
189
190         if (transport_sub_state & StopPendingCapture) {
191                 /* force a declick out */
192                 declick = -1;
193         }
194
195         const nframes_t start_frame = _transport_frame;
196         const nframes_t end_frame = _transport_frame + lrintf(nframes * _transport_speed);
197
198         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
199
200                 int ret;
201
202                 if ((*i)->is_hidden()) {
203                         continue;
204                 }
205
206                 if ((ret = (*i)->silent_roll (nframes, start_frame, end_frame, record_active, rec_monitors)) < 0) {
207
208                         /* we have to do this here. Route::roll() for an AudioTrack will have called AudioDiskstream::process(),
209                            and the DS will expect AudioDiskstream::commit() to be called. but we're aborting from that
210                            call path, so make sure we release any outstanding locks here before we return failure.
211                         */
212
213                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
214                         for (DiskstreamList::iterator ids = dsl->begin(); ids != dsl->end(); ++ids) {
215                                 (*ids)->recover ();
216                         }
217
218                         stop_transport ();
219                         return -1;
220                 }
221         }
222
223         return 0;
224 }
225
226 void
227 Session::commit_diskstreams (nframes_t nframes, bool &needs_butler)
228 {
229         int dret;
230         float pworst = 1.0f;
231         float cworst = 1.0f;
232
233         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
234         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
235
236                 if ((*i)->hidden()) {
237                         continue;
238                 }
239
240                 /* force all diskstreams not handled by a Route to call do their stuff.
241                    Note: the diskstreams that were handled by a route will just return zero
242                    from this call, because they know they were processed. So in fact, this
243                    also runs commit() for every diskstream.
244                  */
245
246                 if ((dret = (*i)->process (_transport_frame, nframes, actively_recording(), get_rec_monitors_input())) == 0) {
247                         if ((*i)->commit (nframes)) {
248                                 needs_butler = true;
249                         }
250
251                 } else if (dret < 0) {
252                         (*i)->recover();
253                 }
254
255                 pworst = min (pworst, (*i)->playback_buffer_load());
256                 cworst = min (cworst, (*i)->capture_buffer_load());
257         }
258
259         uint32_t pmin = g_atomic_int_get (&_playback_load);
260         uint32_t pminold = g_atomic_int_get (&_playback_load_min);
261         uint32_t cmin = g_atomic_int_get (&_capture_load);
262         uint32_t cminold = g_atomic_int_get (&_capture_load_min);
263
264         g_atomic_int_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
265         g_atomic_int_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
266         g_atomic_int_set (&_playback_load_min, min (pmin, pminold));
267         g_atomic_int_set (&_capture_load_min, min (cmin, cminold));
268
269         if (actively_recording()) {
270                 set_dirty();
271         }
272 }
273
274 /** Process callback used when the auditioner is not active */
275 void
276 Session::process_with_events (nframes_t nframes)
277 {
278         SessionEvent*         ev;
279         nframes_t      this_nframes;
280         nframes_t      end_frame;
281         bool           session_needs_butler = false;
282         nframes_t      stop_limit;
283         long           frames_moved;
284
285         /* make sure the auditioner is silent */
286
287         if (auditioner) {
288                 auditioner->silence (nframes);
289         }
290
291         /* handle any pending events */
292
293         while (pending_events.read (&ev, 1) == 1) {
294                 merge_event (ev);
295         }
296
297         /* if we are not in the middle of a state change,
298            and there are immediate events queued up,
299            process them.
300         */
301
302         while (!non_realtime_work_pending() && !immediate_events.empty()) {
303                 SessionEvent *ev = immediate_events.front ();
304                 immediate_events.pop_front ();
305                 process_event (ev);
306         }
307
308         /* Events caused a transport change, send an MTC Full Frame (Timecode) message.
309          * This is sent whether rolling or not, to give slaves an idea of ardour time
310          * on locates (and allow slow slaves to position and prepare for rolling)
311          */
312         if (_send_timecode_update) {
313                 send_full_time_code(nframes);
314                 deliver_mmc (MIDI::MachineControl::cmdLocate, _transport_frame);
315         }
316
317         if (!process_can_proceed()) {
318                 _silent = true;
319                 return;
320         }
321
322         if (events.empty() || next_event == events.end()) {
323                 process_without_events (nframes);
324                 return;
325         }
326
327         if (_transport_speed == 1.0) {
328                 frames_moved = (long) nframes;
329         } else {
330                 interpolation.set_target_speed (fabs(_target_transport_speed));
331                 interpolation.set_speed (fabs(_transport_speed));
332                 frames_moved = (long) interpolation.interpolate (0, nframes, 0, 0);
333         }
334
335         end_frame = _transport_frame + (nframes_t)frames_moved;
336
337         {
338                 SessionEvent* this_event;
339                 Events::iterator the_next_one;
340
341                 if (!process_can_proceed()) {
342                         _silent = true;
343                         return;
344                 }
345
346                 if (!_exporting && _slave) {
347                         if (!follow_slave (nframes)) {
348                                 return;
349                         }
350                 }
351
352                 if (_transport_speed == 0) {
353                         no_roll (nframes);
354                         return;
355                 }
356
357                 if (!_exporting) {
358                         send_midi_time_code_for_cycle (nframes);
359                 }
360
361                 if (actively_recording()) {
362                         stop_limit = max_frames;
363                 } else {
364
365                         if (Config->get_stop_at_session_end()) {
366                                 stop_limit = current_end_frame();
367                         } else {
368                                 stop_limit = max_frames;
369                         }
370                 }
371
372                 if (maybe_stop (stop_limit)) {
373                         no_roll (nframes);
374                         return;
375                 }
376
377                 this_event = *next_event;
378                 the_next_one = next_event;
379                 ++the_next_one;
380
381                 /* yes folks, here it is, the actual loop where we really truly
382                    process some audio
383                 */
384
385                 while (nframes) {
386
387                         this_nframes = nframes; /* real (jack) time relative */
388                         frames_moved = (long) floor (_transport_speed * nframes); /* transport relative */
389
390                         /* running an event, position transport precisely to its time */
391                         if (this_event && this_event->action_frame <= end_frame && this_event->action_frame >= _transport_frame) {
392                                 /* this isn't quite right for reverse play */
393                                 frames_moved = (long) (this_event->action_frame - _transport_frame);
394                                 this_nframes = (nframes_t) abs( floor(frames_moved / _transport_speed) );
395                         }
396
397                         if (this_nframes) {
398
399                                 click (_transport_frame, this_nframes);
400
401                                 /* now process frames between now and the first event in this block */
402                                 prepare_diskstreams ();
403
404                                 if (process_routes (this_nframes)) {
405                                         fail_roll (nframes);
406                                         return;
407                                 }
408
409                                 commit_diskstreams (this_nframes, session_needs_butler);
410
411                                 nframes -= this_nframes;
412
413                                 if (frames_moved < 0) {
414                                         decrement_transport_position (-frames_moved);
415                                 } else {
416                                         increment_transport_position (frames_moved);
417                                 }
418
419                                 maybe_stop (stop_limit);
420                                 check_declick_out ();
421                         }
422
423                         _engine.split_cycle (this_nframes);
424
425                         /* now handle this event and all others scheduled for the same time */
426
427                         while (this_event && this_event->action_frame == _transport_frame) {
428                                 process_event (this_event);
429
430                                 if (the_next_one == events.end()) {
431                                         this_event = 0;
432                                 } else {
433                                         this_event = *the_next_one;
434                                         ++the_next_one;
435                                 }
436                         }
437
438                         /* if an event left our state changing, do the right thing */
439
440                         if (nframes && non_realtime_work_pending()) {
441                                 no_roll (nframes);
442                                 break;
443                         }
444
445                         /* this is necessary to handle the case of seamless looping */
446                         end_frame = _transport_frame + (nframes_t) floor (nframes * _transport_speed);
447
448                 }
449
450                 set_next_event ();
451
452         } /* implicit release of route lock */
453
454         if (session_needs_butler) {
455                 _butler->summon ();
456         }
457 }
458
459 void
460 Session::reset_slave_state ()
461 {
462         average_slave_delta = 1800;
463         delta_accumulator_cnt = 0;
464         have_first_delta_accumulator = false;
465         _slave_state = Stopped;
466 }
467
468 bool
469 Session::transport_locked () const
470 {
471         Slave* sl = _slave;
472
473         if (!locate_pending() && (!config.get_external_sync() || (sl && sl->ok() && sl->locked()))) {
474                 return true;
475         }
476
477         return false;
478 }
479
480 bool
481 Session::follow_slave (nframes_t nframes)
482 {
483         double slave_speed;
484         nframes64_t slave_transport_frame;
485         nframes_t this_delta;
486         int dir;
487
488         if (!_slave->ok()) {
489                 stop_transport ();
490                 config.set_external_sync (false);
491                 goto noroll;
492         }
493
494         _slave->speed_and_position (slave_speed, slave_transport_frame);
495
496         DEBUG_TRACE (DEBUG::Slave, string_compose ("Slave position %1 speed %2\n", slave_transport_frame, slave_speed));
497
498         if (!_slave->locked()) {
499                 DEBUG_TRACE (DEBUG::Slave, "slave not locked\n");
500                 goto noroll;
501         }
502
503         if (slave_transport_frame > _transport_frame) {
504                 this_delta = slave_transport_frame - _transport_frame;
505                 dir = 1;
506         } else {
507                 this_delta = _transport_frame - slave_transport_frame;
508                 dir = -1;
509         }
510
511         if (_slave->starting()) {
512                 slave_speed = 0.0f;
513         }
514
515         if (_slave->is_always_synced() || config.get_timecode_source_is_synced()) {
516
517                 /* if the TC source is synced, then we assume that its
518                    speed is binary: 0.0 or 1.0
519                 */
520
521                 if (slave_speed != 0.0f) {
522                         slave_speed = 1.0f;
523                 }
524
525         } else {
526
527                 /* if we are chasing and the average delta between us and the
528                    master gets too big, we want to switch to silent
529                    motion. so keep track of that here.
530                 */
531
532                 if (_slave_state == Running) {
533                         calculate_moving_average_of_slave_delta(dir, this_delta);
534                 }
535         }
536
537         track_slave_state (slave_speed, slave_transport_frame, this_delta);
538
539         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave state %1 @ %2 speed %3 cur delta %4 avg delta %5\n",
540                                                    _slave_state, slave_transport_frame, slave_speed, this_delta, average_slave_delta));
541                      
542
543         if (_slave_state == Running && !_slave->is_always_synced() && !config.get_timecode_source_is_synced()) {
544
545                 if (_transport_speed != 0.0f) {
546
547                         /*
548                            note that average_dir is +1 or -1
549                         */
550
551                         float delta;
552
553                         if (average_slave_delta == 0) {
554                                 delta = this_delta;
555                                 delta *= dir;
556                         } else {
557                                 delta = average_slave_delta;
558                                 delta *= average_dir;
559                         }
560
561 #ifndef NDEBUG
562                         if (slave_speed != 0.0) {
563                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("delta = %1 speed = %2 ts = %3 M@%4 S@%5 avgdelta %6\n",
564                                                                            (int) (dir * this_delta),
565                                                                            slave_speed,
566                                                                            _transport_speed,
567                                                                            _transport_frame,
568                                                                            slave_transport_frame, 
569                                                                            average_slave_delta));
570                         }
571 #endif
572                         
573                         if (_slave->give_slave_full_control_over_transport_speed()) {
574                                 set_transport_speed (slave_speed, false, false);
575                         } else {
576                                 float adjusted_speed = slave_speed + (1.5 * (delta /  float(_current_frame_rate)));
577                                 request_transport_speed (adjusted_speed);
578                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("adjust using %1 towards %2 ratio %3 current %4 slave @ %5\n",
579                                                                            delta, adjusted_speed, adjusted_speed/slave_speed, _transport_speed,
580                                                                            slave_speed));
581                         }
582                         
583                         if (abs(average_slave_delta) > _slave->resolution()) {
584                                 cerr << "average slave delta greater than slave resolution (" << _slave->resolution() << "), going to silent motion\n";
585                                 goto silent_motion;
586                         }
587                 }
588         }
589
590
591         if (_slave_state == Running && !non_realtime_work_pending()) {
592                 /* speed is set, we're locked, and good to go */
593                 return true;
594         }
595
596   silent_motion:
597         DEBUG_TRACE (DEBUG::Slave, "silent motion\n")
598         follow_slave_silently (nframes, slave_speed);
599
600   noroll:
601         /* don't move at all */
602         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
603         no_roll (nframes);
604         return false;
605 }
606
607 void
608 Session::calculate_moving_average_of_slave_delta(int dir, nframes_t this_delta)
609 {
610         if (delta_accumulator_cnt >= delta_accumulator_size) {
611                 have_first_delta_accumulator = true;
612                 delta_accumulator_cnt = 0;
613         }
614
615         if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
616                 delta_accumulator[delta_accumulator_cnt++] = long(dir) * long(this_delta);
617         }
618
619         if (have_first_delta_accumulator) {
620                 average_slave_delta = 0L;
621                 for (int i = 0; i < delta_accumulator_size; ++i) {
622                         average_slave_delta += delta_accumulator[i];
623                 }
624                 average_slave_delta /= long(delta_accumulator_size);
625                 if (average_slave_delta < 0L) {
626                         average_dir = -1;
627                         average_slave_delta = abs(average_slave_delta);
628                 } else {
629                         average_dir = 1;
630                 }
631         }
632 }
633
634 void
635 Session::track_slave_state (float slave_speed, nframes_t slave_transport_frame, nframes_t this_delta)
636 {
637         if (slave_speed != 0.0f) {
638
639                 /* slave is running */
640
641                 switch (_slave_state) {
642                 case Stopped:
643                         if (_slave->requires_seekahead()) {
644                                 slave_wait_end = slave_transport_frame + _slave->seekahead_distance ();
645                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, but running, requires seekahead to %1\n", slave_wait_end));
646                                 /* we can call locate() here because we are in process context */
647                                 locate (slave_wait_end, false, false);
648                                 _slave_state = Waiting;
649
650                         } else {
651
652                                 _slave_state = Running;
653
654                                 Location* al = _locations.auto_loop_location();
655
656                                 if (al && play_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
657                                         // cancel looping
658                                         request_play_loop(false);
659                                 }
660
661                                 if (slave_transport_frame != _transport_frame) {
662                                         locate (slave_transport_frame, false, false);
663                                 }
664                         }
665                         break;
666
667                 case Waiting:
668                 default:
669                         break;
670                 }
671
672                 if (_slave_state == Waiting) {
673
674                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave waiting at %1\n", slave_transport_frame));
675
676                         if (slave_transport_frame >= slave_wait_end) {
677
678                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave start at %1 vs %2\n", slave_transport_frame, _transport_frame));
679
680                                 _slave_state = Running;
681
682                                 /* now perform a "micro-seek" within the disk buffers to realign ourselves
683                                    precisely with the master.
684                                 */
685
686
687                                 bool ok = true;
688                                 nframes_t frame_delta = slave_transport_frame - _transport_frame;
689
690                                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
691
692                                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
693                                         if (!(*i)->can_internal_playback_seek (frame_delta)) {
694                                                 ok = false;
695                                                 break;
696                                         }
697                                 }
698
699                                 if (ok) {
700                                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
701                                                 (*i)->internal_playback_seek (frame_delta);
702                                         }
703                                         _transport_frame += frame_delta;
704
705                                 } else {
706                                         cerr << "cannot micro-seek\n";
707                                         /* XXX what? */
708                                 }
709
710                                 memset (delta_accumulator, 0, sizeof (long) * delta_accumulator_size);
711                                 average_slave_delta = 0L;
712                                 this_delta = 0;
713                         }
714                 }
715
716                 if (_slave_state == Running && _transport_speed == 0.0f) {
717                         DEBUG_TRACE (DEBUG::Slave, "slave starts transport\n");
718                         start_transport ();
719                 }
720
721         } else { // slave_speed is 0
722
723                 /* slave has stopped */
724
725                 if (_transport_speed != 0.0f) {
726                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 frame %2 tf %3\n", slave_speed, slave_transport_frame, _transport_frame));
727                         stop_transport();
728                 }
729
730                 if (slave_transport_frame != _transport_frame) {
731                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, move to %1\n", slave_transport_frame));
732                         force_locate (slave_transport_frame, false);
733                 }
734
735                 _slave_state = Stopped;
736         }
737 }
738
739 void
740 Session::follow_slave_silently (nframes_t nframes, float slave_speed)
741 {
742         if (slave_speed && _transport_speed) {
743
744                 /* something isn't right, but we should move with the master
745                    for now.
746                 */
747
748                 bool need_butler;
749
750                 prepare_diskstreams ();
751                 silent_process_routes (nframes);
752                 commit_diskstreams (nframes, need_butler);
753
754                 if (need_butler) {
755                         _butler->summon ();
756                 }
757
758                 int32_t frames_moved = (int32_t) floor (_transport_speed * nframes);
759
760                 if (frames_moved < 0) {
761                         decrement_transport_position (-frames_moved);
762                 } else {
763                         increment_transport_position (frames_moved);
764                 }
765
766                 nframes_t stop_limit;
767
768                 if (actively_recording()) {
769                         stop_limit = max_frames;
770                 } else {
771                         if (Config->get_stop_at_session_end()) {
772                                 stop_limit = current_end_frame();
773                         } else {
774                                 stop_limit = max_frames;
775                         }
776                 }
777
778                 maybe_stop (stop_limit);
779         }
780 }
781
782 void
783 Session::process_without_events (nframes_t nframes)
784 {
785         bool session_needs_butler = false;
786         nframes_t stop_limit;
787         long frames_moved;
788
789         if (!process_can_proceed()) {
790                 _silent = true;
791                 return;
792         }
793
794         if (!_exporting && _slave) {
795                 if (!follow_slave (nframes)) {
796                         return;
797                 }
798         }
799
800         if (_transport_speed == 0) {
801                 fail_roll (nframes);
802                 return;
803         }
804
805         if (!_exporting) {
806                 send_midi_time_code_for_cycle (nframes);
807         }
808
809         if (actively_recording()) {
810                 stop_limit = max_frames;
811         } else {
812                 if (Config->get_stop_at_session_end()) {
813                         stop_limit = current_end_frame();
814                 } else {
815                         stop_limit = max_frames;
816                 }
817         }
818
819         if (maybe_stop (stop_limit)) {
820                 fail_roll (nframes);
821                 return;
822         }
823
824         if (maybe_sync_start (nframes)) {
825                 return;
826         }
827
828         click (_transport_frame, nframes);
829
830         prepare_diskstreams ();
831
832         if (_transport_speed == 1.0) {
833                 frames_moved = (long) nframes;
834         } else {
835                 interpolation.set_target_speed (fabs(_target_transport_speed));
836                 interpolation.set_speed (fabs(_transport_speed));
837                 frames_moved = (long) interpolation.interpolate (0, nframes, 0, 0);
838         }
839
840         if (process_routes (nframes)) {
841                 fail_roll (nframes);
842                 return;
843         }
844
845         commit_diskstreams (nframes, session_needs_butler);
846
847         if (frames_moved < 0) {
848                 decrement_transport_position (-frames_moved);
849         } else {
850                 increment_transport_position (frames_moved);
851         }
852
853         maybe_stop (stop_limit);
854         check_declick_out ();
855
856         if (session_needs_butler) {
857                 _butler->summon ();
858         }
859 }
860
861 /** Process callback used when the auditioner is active.
862  * @param nframes number of frames to process.
863  */
864 void
865 Session::process_audition (nframes_t nframes)
866 {
867         SessionEvent* ev;
868         boost::shared_ptr<RouteList> r = routes.reader ();
869
870         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
871                 if (!(*i)->is_hidden()) {
872                         (*i)->silence (nframes);
873                 }
874         }
875
876         /* run the auditioner, and if it says we need butler service, ask for it */
877
878         if (auditioner->play_audition (nframes) > 0) {
879                 _butler->summon ();
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->active()) {
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 (nframes_t& nframes)
907 {
908         nframes_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_port_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                         start_locate (ev->target_frame, true, false, Config->get_seamless_loop());
1019                 }
1020                 remove = false;
1021                 del = false;
1022                 break;
1023
1024         case SessionEvent::Locate:
1025                 if (ev->yes_or_no) {
1026                         // cerr << "forced locate to " << ev->target_frame << endl;
1027                         locate (ev->target_frame, false, true, false);
1028                 } else {
1029                         // cerr << "soft locate to " << ev->target_frame << endl;
1030                         start_locate (ev->target_frame, false, true, false);
1031                 }
1032                 _send_timecode_update = true;
1033                 break;
1034
1035         case SessionEvent::LocateRoll:
1036                 if (ev->yes_or_no) {
1037                         // cerr << "forced locate to+roll " << ev->target_frame << endl;
1038                         locate (ev->target_frame, true, true, false);
1039                 } else {
1040                         // cerr << "soft locate to+roll " << ev->target_frame << endl;
1041                         start_locate (ev->target_frame, true, true, false);
1042                 }
1043                 _send_timecode_update = true;
1044                 break;
1045
1046         case SessionEvent::LocateRollLocate:
1047                 // locate is handled by ::request_roll_at_and_return()
1048                 _requested_return_frame = ev->target_frame;
1049                 request_locate (ev->target2_frame, true);
1050                 break;
1051
1052
1053         case SessionEvent::SetTransportSpeed:
1054                 set_transport_speed (ev->speed, ev->yes_or_no, ev->second_yes_or_no);
1055                 break;
1056
1057         case SessionEvent::PunchIn:
1058                 // cerr << "PunchIN at " << transport_frame() << endl;
1059                 if (config.get_punch_in() && record_status() == Enabled) {
1060                         enable_record ();
1061                 }
1062                 remove = false;
1063                 del = false;
1064                 break;
1065
1066         case SessionEvent::PunchOut:
1067                 // cerr << "PunchOUT at " << transport_frame() << endl;
1068                 if (config.get_punch_out()) {
1069                         step_back_from_record ();
1070                 }
1071                 remove = false;
1072                 del = false;
1073                 break;
1074
1075         case SessionEvent::StopOnce:
1076                 if (!non_realtime_work_pending()) {
1077                         stop_transport (ev->yes_or_no);
1078                         _clear_event_type (SessionEvent::StopOnce);
1079                 }
1080                 remove = false;
1081                 del = false;
1082                 break;
1083
1084         case SessionEvent::RangeStop:
1085                 if (!non_realtime_work_pending()) {
1086                         stop_transport (ev->yes_or_no);
1087                 }
1088                 remove = false;
1089                 del = false;
1090                 break;
1091
1092         case SessionEvent::RangeLocate:
1093                 start_locate (ev->target_frame, true, true, false);
1094                 remove = false;
1095                 del = false;
1096                 break;
1097
1098         case SessionEvent::Overwrite:
1099                 overwrite_some_buffers (static_cast<Diskstream*>(ev->ptr));
1100                 break;
1101
1102         case SessionEvent::SetDiskstreamSpeed:
1103                 set_diskstream_speed (static_cast<Diskstream*> (ev->ptr), ev->speed);
1104                 break;
1105
1106         case SessionEvent::SetSyncSource:
1107                 use_sync_source (ev->slave);
1108                 break;
1109
1110         case SessionEvent::Audition:
1111                 set_audition (ev->region);
1112                 // drop reference to region
1113                 ev->region.reset ();
1114                 break;
1115
1116         case SessionEvent::InputConfigurationChange:
1117                 add_post_transport_work (PostTransportInputChange);
1118                 _butler->schedule_transport_work ();
1119                 break;
1120
1121         case SessionEvent::SetPlayAudioRange:
1122                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
1123                 break;
1124
1125         case SessionEvent::RealTimeOperation:
1126                 process_rtop (ev);
1127                 del = false; // other side of RT request needs to clean up
1128                 break;
1129
1130         default:
1131           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
1132                 /*NOTREACHED*/
1133                 break;
1134         };
1135
1136         if (remove) {
1137                 del = del && !_remove_event (ev);
1138         }
1139
1140         if (del) {
1141                 delete ev;
1142         }
1143 }
1144
1145 void
1146 Session::process_rtop (SessionEvent* ev)
1147 {
1148         ev->rt_slot ();
1149         ev->rt_return (ev);
1150 }