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