d16f7d3b0cad3f6ee12ed624e28e28467f865454
[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 samples to process.
57  */
58
59 void
60 Session::process (pframes_t nframes)
61 {
62         samplepos_t transport_at_start = _transport_sample;
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 sample
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         samplepos_t end_sample = _transport_sample + 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_sample, end_sample, _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_sample, 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_sample, end_sample, 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_sample, end_sample, 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 samplepos_t start_sample = _transport_sample;
189         const samplepos_t end_sample = _transport_sample + 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_sample, 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_sample, end_sample, 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_sample, end_sample, 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         samplepos_t     end_sample;
269         bool           session_needs_butler = false;
270         samplecnt_t     samples_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         /* only count-in when going to roll at speed 1.0 */
296         if (_transport_speed != 1.0 && _count_in_samples > 0) {
297                 _count_in_samples = 0;
298         }
299         if (_transport_speed == 0.0) {
300                 _remaining_latency_preroll = 0;
301         }
302
303         assert (_count_in_samples == 0 || _remaining_latency_preroll == 0 || _count_in_samples == _remaining_latency_preroll);
304
305         if (_count_in_samples > 0 || _remaining_latency_preroll > 0) {
306                 samplecnt_t ns;
307
308                 if (_remaining_latency_preroll > 0) {
309                         ns = std::min ((samplecnt_t)nframes, _remaining_latency_preroll);
310                 } else {
311                         ns = std::min ((samplecnt_t)nframes, _count_in_samples);
312                 }
313
314                 boost::shared_ptr<RouteList> r = routes.reader ();
315                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
316                         samplecnt_t route_offset = (*i)->playback_latency ();
317                         if (_remaining_latency_preroll > route_offset + ns) {
318                                 /* route will no-roll for complete pre-roll cycle */
319                                 continue;
320                         }
321                         if (_remaining_latency_preroll > route_offset) {
322                                 /* route may need partial no-roll and partial roll from
323                                 * (_transport_sample - _remaining_latency_preroll) ..  +ns.
324                                 * shorten and split the cycle.
325                                 */
326                                 ns = std::min (ns, (_remaining_latency_preroll - route_offset));
327                         }
328                 }
329
330                 if (_count_in_samples > 0) {
331                         run_click (_transport_sample - _count_in_samples, ns);
332                         assert (_count_in_samples >= ns);
333                         _count_in_samples -= ns;
334                 }
335
336                 if (_remaining_latency_preroll > 0) {
337                         if (_count_in_samples == 0) {
338                                 click (_transport_sample - _remaining_latency_preroll, ns);
339                         }
340                         if (process_routes (ns, session_needs_butler)) {
341                                 fail_roll (ns);
342                         }
343                 } else {
344                         no_roll (ns);
345                 }
346
347                 if (_remaining_latency_preroll > 0) {
348                         assert (_remaining_latency_preroll >= ns);
349                         _remaining_latency_preroll -= ns;
350                 }
351
352                 nframes -= ns;
353
354                 /* process events.. */
355                 if (!events.empty() && next_event != events.end()) {
356                         SessionEvent* this_event = *next_event;
357                         Events::iterator the_next_one = next_event;
358                         ++the_next_one;
359
360                         while (this_event && this_event->action_sample == _transport_sample) {
361                                 process_event (this_event);
362                                 if (the_next_one == events.end()) {
363                                         this_event = 0;
364                                 } else {
365                                         this_event = *the_next_one;
366                                         ++the_next_one;
367                                 }
368                         }
369                         set_next_event ();
370                 }
371
372                 check_declick_out ();
373
374                 if (nframes == 0) {
375                         return;
376                 } else {
377                         _engine.split_cycle (ns);
378                 }
379         }
380
381         /* Decide on what to do with quarter-frame MTC during this cycle */
382
383         bool const was_sending_qf_mtc = _send_qf_mtc;
384         double const tolerance = Config->get_mtc_qf_speed_tolerance() / 100.0;
385
386         if (_transport_speed != 0) {
387                 _send_qf_mtc = (
388                         Config->get_send_mtc () &&
389                         _transport_speed >= (1 - tolerance) &&
390                         _transport_speed <= (1 + tolerance)
391                         );
392
393                 if (_send_qf_mtc && !was_sending_qf_mtc) {
394                         /* we will re-start quarter-frame MTC this cycle, so send a full update to set things up */
395                         _send_timecode_update = true;
396                 }
397
398                 if (Config->get_send_mtc() && !_send_qf_mtc && _pframes_since_last_mtc > (sample_rate () / 4)) {
399                         /* we're sending MTC, but we're not sending QF MTC at the moment, and it's been
400                            a quarter of a second since we sent anything at all, so send a full MTC update
401                            this cycle.
402                         */
403                         _send_timecode_update = true;
404                 }
405
406                 _pframes_since_last_mtc += nframes;
407         }
408
409         /* Events caused a transport change (or we re-started sending
410          * MTC), so send an MTC Full Frame (Timecode) message.  This
411          * is sent whether rolling or not, to give slaves an idea of
412          * ardour time on locates (and allow slow slaves to position
413          * and prepare for rolling)
414          */
415         if (_send_timecode_update) {
416                 send_full_time_code (_transport_sample, nframes);
417         }
418
419         if (!process_can_proceed()) {
420                 _silent = true;
421                 return;
422         }
423
424         if (events.empty() || next_event == events.end()) {
425                 try_run_lua (nframes); // also during export ?? ->move to process_without_events()
426                 /* lua scripts may inject events */
427                 while (_n_lua_scripts > 0 && pending_events.read (&ev, 1) == 1) {
428                         merge_event (ev);
429                 }
430                 if (events.empty() || next_event == events.end()) {
431                         process_without_events (nframes);
432                         return;
433                 }
434         }
435
436         if (_transport_speed == 1.0) {
437                 samples_moved = (samplecnt_t) nframes;
438         } else {
439                 /* use a cubic midi interpolation to compute the number of
440                  * samples we will move at the current speed.
441                  */
442                 CubicInterpolation interp;
443                 interp.set_speed (_transport_speed);
444                 samples_moved = interp.distance (nframes);
445         }
446
447         end_sample = _transport_sample + samples_moved;
448
449         {
450                 SessionEvent* this_event;
451                 Events::iterator the_next_one;
452
453                 if (!process_can_proceed()) {
454                         _silent = true;
455                         return;
456                 }
457
458                 if (!_exporting && _slave) {
459                         if (!follow_slave (nframes)) {
460                                 return;
461                         }
462                 }
463
464                 if (_transport_speed == 0) {
465                         no_roll (nframes);
466                         return;
467                 }
468
469                 if (!_exporting && !timecode_transmission_suspended()) {
470                         send_midi_time_code_for_cycle (_transport_sample, end_sample, nframes);
471                 }
472
473                 ltc_tx_send_time_code_for_cycle (_transport_sample, end_sample, _target_transport_speed, _transport_speed, nframes);
474
475                 samplepos_t stop_limit = compute_stop_limit ();
476
477                 if (maybe_stop (stop_limit)) {
478                         no_roll (nframes);
479                         return;
480                 }
481
482                 this_event = *next_event;
483                 the_next_one = next_event;
484                 ++the_next_one;
485
486                 /* yes folks, here it is, the actual loop where we really truly
487                    process some audio
488                 */
489
490                 while (nframes) {
491
492                         this_nframes = nframes; /* real (jack) time relative */
493                         samples_moved = (samplecnt_t) floor (_transport_speed * nframes); /* transport relative */
494
495                         /* running an event, position transport precisely to its time */
496                         if (this_event && this_event->action_sample <= end_sample && this_event->action_sample >= _transport_sample) {
497                                 /* this isn't quite right for reverse play */
498                                 samples_moved = (samplecnt_t) (this_event->action_sample - _transport_sample);
499                                 this_nframes = abs (floor(samples_moved / _transport_speed));
500                         }
501
502                         try_run_lua (this_nframes);
503
504                         if (this_nframes) {
505
506                                 click (_transport_sample, this_nframes);
507
508                                 if (process_routes (this_nframes, session_needs_butler)) {
509                                         fail_roll (nframes);
510                                         return;
511                                 }
512
513                                 get_track_statistics ();
514
515                                 nframes -= this_nframes;
516
517                                 if (samples_moved < 0) {
518                                         decrement_transport_position (-samples_moved);
519                                 } else if (samples_moved) {
520                                         increment_transport_position (samples_moved);
521                                 }
522
523                                 maybe_stop (stop_limit);
524                                 check_declick_out ();
525                         }
526
527                         if (nframes > 0) {
528                                 _engine.split_cycle (this_nframes);
529                         }
530
531                         /* now handle this event and all others scheduled for the same time */
532
533                         while (this_event && this_event->action_sample == _transport_sample) {
534                                 process_event (this_event);
535
536                                 if (the_next_one == events.end()) {
537                                         this_event = 0;
538                                 } else {
539                                         this_event = *the_next_one;
540                                         ++the_next_one;
541                                 }
542                         }
543
544                         /* if an event left our state changing, do the right thing */
545
546                         if (nframes && non_realtime_work_pending()) {
547                                 no_roll (nframes);
548                                 break;
549                         }
550
551                         /* this is necessary to handle the case of seamless looping */
552                         end_sample = _transport_sample + floor (nframes * _transport_speed);
553                 }
554
555                 set_next_event ();
556
557         } /* implicit release of route lock */
558
559         if (session_needs_butler) {
560                 DEBUG_TRACE (DEBUG::Butler, "p-with-events: session needs butler, call it\n");
561                 _butler->summon ();
562         }
563 }
564
565 void
566 Session::reset_slave_state ()
567 {
568         average_slave_delta = 1800;
569         delta_accumulator_cnt = 0;
570         have_first_delta_accumulator = false;
571         _slave_state = Stopped;
572         DiskReader::set_no_disk_output (false);
573 }
574
575 bool
576 Session::transport_locked () const
577 {
578         Slave* sl = _slave;
579
580         if (!locate_pending() && (!config.get_external_sync() || (sl && sl->ok() && sl->locked()))) {
581                 return true;
582         }
583
584         return false;
585 }
586
587 bool
588 Session::follow_slave (pframes_t nframes)
589 {
590         double slave_speed;
591         samplepos_t slave_transport_sample;
592         samplecnt_t this_delta;
593         int dir;
594
595         if (!_slave->ok()) {
596                 stop_transport ();
597                 config.set_external_sync (false);
598                 goto noroll;
599         }
600
601         _slave->speed_and_position (slave_speed, slave_transport_sample);
602
603         DEBUG_TRACE (DEBUG::Slave, string_compose ("Slave position %1 speed %2\n", slave_transport_sample, slave_speed));
604
605         if (!_slave->locked()) {
606                 DEBUG_TRACE (DEBUG::Slave, "slave not locked\n");
607                 goto noroll;
608         }
609
610         if (slave_transport_sample > _transport_sample) {
611                 this_delta = slave_transport_sample - _transport_sample;
612                 dir = 1;
613         } else {
614                 this_delta = _transport_sample - slave_transport_sample;
615                 dir = -1;
616         }
617
618         if (_slave->starting()) {
619                 slave_speed = 0.0f;
620         }
621
622         if (_slave->is_always_synced() ||
623                         (Config->get_timecode_source_is_synced() && (dynamic_cast<TimecodeSlave*>(_slave)) != 0)
624                         ) {
625
626                 /* if the TC source is synced, then we assume that its
627                    speed is binary: 0.0 or 1.0
628                 */
629
630                 if (slave_speed != 0.0f) {
631                         slave_speed = 1.0f;
632                 }
633
634         } else {
635
636                 /* if we are chasing and the average delta between us and the
637                    master gets too big, we want to switch to silent
638                    motion. so keep track of that here.
639                 */
640
641                 if (_slave_state == Running) {
642                         calculate_moving_average_of_slave_delta(dir, abs(this_delta));
643                 }
644         }
645
646         track_slave_state (slave_speed, slave_transport_sample, this_delta);
647
648         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave state %1 @ %2 speed %3 cur delta %4 avg delta %5\n",
649                                                    _slave_state, slave_transport_sample, slave_speed, this_delta, average_slave_delta));
650
651
652         if (_slave_state == Running && !_slave->is_always_synced() && !(Config->get_timecode_source_is_synced() && (dynamic_cast<TimecodeSlave*>(_slave)) != 0)) {
653
654                 /* may need to varispeed to sync with slave */
655
656                 if (_transport_speed != 0.0f) {
657
658                         /*
659                            note that average_dir is +1 or -1
660                         */
661
662                         float delta;
663
664                         if (average_slave_delta == 0) {
665                                 delta = this_delta;
666                                 delta *= dir;
667                         } else {
668                                 delta = average_slave_delta;
669                                 delta *= average_dir;
670                         }
671
672 #ifndef NDEBUG
673                         if (slave_speed != 0.0) {
674                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("delta = %1 speed = %2 ts = %3 M@%4 S@%5 avgdelta %6\n",
675                                                                            (int) (dir * this_delta),
676                                                                            slave_speed,
677                                                                            _transport_speed,
678                                                                            _transport_sample,
679                                                                            slave_transport_sample,
680                                                                            average_slave_delta));
681                         }
682 #endif
683
684                         if (_slave->give_slave_full_control_over_transport_speed()) {
685                                 set_transport_speed (slave_speed, 0, false, false);
686                                 //std::cout << "set speed = " << slave_speed << "\n";
687                         } else {
688                                 float adjusted_speed = slave_speed + (1.5 * (delta /  float(_current_sample_rate)));
689                                 request_transport_speed (adjusted_speed);
690                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("adjust using %1 towards %2 ratio %3 current %4 slave @ %5\n",
691                                                                            delta, adjusted_speed, adjusted_speed/slave_speed, _transport_speed,
692                                                                            slave_speed));
693                         }
694
695                         if (!actively_recording() && (samplecnt_t) average_slave_delta > _slave->resolution()) {
696                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("average slave delta %1 greater than slave resolution %2 => no disk output\n", average_slave_delta, _slave->resolution()));
697                                 /* run routes as normal, but no disk output */
698                                 DiskReader::set_no_disk_output (true);
699                                 return true;
700                         }
701
702                         if (!have_first_delta_accumulator) {
703                                 DEBUG_TRACE (DEBUG::Slave, "waiting for first slave delta accumulator to be ready, no disk output\n");
704                                 /* run routes as normal, but no disk output */
705                                 DiskReader::set_no_disk_output (true);
706                                 return true;
707                         }
708                 }
709         }
710
711
712         if (!have_first_delta_accumulator) {
713                 DEBUG_TRACE (DEBUG::Slave, "still waiting to compute slave delta, no disk output\n");
714                 DiskReader::set_no_disk_output (true);
715         } else {
716                 DiskReader::set_no_disk_output (false);
717         }
718
719         if ((_slave_state == Running) && (0 == (post_transport_work () & ~PostTransportSpeed))) {
720                 /* speed is set, we're locked, and good to go */
721                 return true;
722         }
723
724   noroll:
725         /* don't move at all */
726         DEBUG_TRACE (DEBUG::Slave, "no roll\n")
727         no_roll (nframes);
728         return false;
729 }
730
731 void
732 Session::calculate_moving_average_of_slave_delta (int dir, samplecnt_t this_delta)
733 {
734         if (delta_accumulator_cnt >= delta_accumulator_size) {
735                 have_first_delta_accumulator = true;
736                 delta_accumulator_cnt = 0;
737         }
738
739         if (delta_accumulator_cnt != 0 || this_delta < _current_sample_rate) {
740                 delta_accumulator[delta_accumulator_cnt++] = (samplecnt_t) dir *  (samplecnt_t) this_delta;
741         }
742
743         if (have_first_delta_accumulator) {
744                 average_slave_delta = 0L;
745                 for (int i = 0; i < delta_accumulator_size; ++i) {
746                         average_slave_delta += delta_accumulator[i];
747                 }
748                 average_slave_delta /= (int32_t) delta_accumulator_size;
749                 if (average_slave_delta < 0L) {
750                         average_dir = -1;
751                         average_slave_delta = average_slave_delta;
752                 } else {
753                         average_dir = 1;
754                 }
755         }
756 }
757
758 void
759 Session::track_slave_state (float slave_speed, samplepos_t slave_transport_sample, samplecnt_t /*this_delta*/)
760 {
761         if (slave_speed != 0.0f) {
762
763                 /* slave is running */
764
765                 switch (_slave_state) {
766                 case Stopped:
767                         if (_slave->requires_seekahead()) {
768                                 slave_wait_end = slave_transport_sample + _slave->seekahead_distance ();
769                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, but running, requires seekahead to %1\n", slave_wait_end));
770                                 /* we can call locate() here because we are in process context */
771                                 locate (slave_wait_end, false, false);
772                                 _slave_state = Waiting;
773
774                         } else {
775
776                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped -> running at %1\n", slave_transport_sample));
777
778                                 memset (delta_accumulator, 0, sizeof (int32_t) * delta_accumulator_size);
779                                 average_slave_delta = 0L;
780
781                                 Location* al = _locations->auto_loop_location();
782
783                                 if (al && play_loop && (slave_transport_sample < al->start() || slave_transport_sample > al->end())) {
784                                         // cancel looping
785                                         request_play_loop(false);
786                                 }
787
788                                 if (slave_transport_sample != _transport_sample) {
789                                         DEBUG_TRACE (DEBUG::Slave, string_compose ("require locate to run. eng: %1 -> sl: %2\n", _transport_sample, slave_transport_sample));
790                                         locate (slave_transport_sample, false, false);
791                                 }
792                                 _slave_state = Running;
793                         }
794                         break;
795
796                 case Waiting:
797                 default:
798                         break;
799                 }
800
801                 if (_slave_state == Waiting) {
802
803                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave waiting at %1\n", slave_transport_sample));
804
805                         if (slave_transport_sample >= slave_wait_end) {
806
807                                 DEBUG_TRACE (DEBUG::Slave, string_compose ("slave start at %1 vs %2\n", slave_transport_sample, _transport_sample));
808
809                                 _slave_state = Running;
810
811                                 /* now perform a "micro-seek" within the disk buffers to realign ourselves
812                                    precisely with the master.
813                                 */
814
815
816                                 bool ok = true;
817                                 samplecnt_t sample_delta = slave_transport_sample - _transport_sample;
818
819                                 boost::shared_ptr<RouteList> rl = routes.reader();
820                                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
821                                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
822                                         if (tr && !tr->can_internal_playback_seek (sample_delta)) {
823                                                 ok = false;
824                                                 break;
825                                         }
826                                 }
827
828                                 if (ok) {
829                                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
830                                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
831                                                 if (tr) {
832                                                         tr->internal_playback_seek (sample_delta);
833                                                 }
834                                         }
835                                         _transport_sample += sample_delta;
836
837                                 } else {
838                                         cerr << "cannot micro-seek\n";
839                                         /* XXX what? */
840                                 }
841                         }
842                 }
843
844                 if (_slave_state == Running && _transport_speed == 0.0f) {
845                         DEBUG_TRACE (DEBUG::Slave, "slave starts transport\n");
846                         start_transport ();
847                 }
848
849         } else { // slave_speed is 0
850
851                 /* slave has stopped */
852
853                 if (_transport_speed != 0.0f) {
854                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stops transport: %1 sample %2 tf %3\n", slave_speed, slave_transport_sample, _transport_sample));
855                         stop_transport ();
856                 }
857
858                 if (slave_transport_sample != _transport_sample) {
859                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave stopped, move to %1\n", slave_transport_sample));
860                         force_locate (slave_transport_sample, false);
861                 }
862
863                 reset_slave_state();
864         }
865 }
866
867 void
868 Session::process_without_events (pframes_t nframes)
869 {
870         bool session_needs_butler = false;
871         samplecnt_t samples_moved;
872
873         if (!process_can_proceed()) {
874                 _silent = true;
875                 return;
876         }
877
878         if (!_exporting && _slave) {
879                 if (!follow_slave (nframes)) {
880                         ltc_tx_send_time_code_for_cycle (_transport_sample, _transport_sample, 0, 0 , nframes);
881                         return;
882                 }
883         }
884
885         if (_transport_speed == 0) {
886                 no_roll (nframes);
887                 return;
888         }
889
890         if (_transport_speed == 1.0) {
891                 samples_moved = (samplecnt_t) nframes;
892         } else {
893                 interpolation.set_speed (_transport_speed);
894                 samples_moved = interpolation.distance (nframes);
895         }
896
897         if (!_exporting && !timecode_transmission_suspended()) {
898                 send_midi_time_code_for_cycle (_transport_sample, _transport_sample + samples_moved, nframes);
899         }
900
901         ltc_tx_send_time_code_for_cycle (_transport_sample, _transport_sample + samples_moved, _target_transport_speed, _transport_speed, nframes);
902
903         samplepos_t const stop_limit = compute_stop_limit ();
904
905         if (maybe_stop (stop_limit)) {
906                 no_roll (nframes);
907                 return;
908         }
909
910         if (maybe_sync_start (nframes)) {
911                 return;
912         }
913
914         click (_transport_sample, nframes);
915
916         if (process_routes (nframes, session_needs_butler)) {
917                 fail_roll (nframes);
918                 return;
919         }
920
921         get_track_statistics ();
922
923         if (samples_moved < 0) {
924                 decrement_transport_position (-samples_moved);
925         } else if (samples_moved) {
926                 increment_transport_position (samples_moved);
927         }
928
929         maybe_stop (stop_limit);
930         check_declick_out ();
931
932         if (session_needs_butler) {
933                 DEBUG_TRACE (DEBUG::Butler, "p-without-events: session needs butler, call it\n");
934                 _butler->summon ();
935         }
936 }
937
938 /** Process callback used when the auditioner is active.
939  * @param nframes number of samples to process.
940  */
941 void
942 Session::process_audition (pframes_t nframes)
943 {
944         SessionEvent* ev;
945         boost::shared_ptr<RouteList> r = routes.reader ();
946
947         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
948                 if (!(*i)->is_auditioner()) {
949                         (*i)->silence (nframes);
950                 }
951         }
952
953         /* run the auditioner, and if it says we need butler service, ask for it */
954
955         if (auditioner->play_audition (nframes) > 0) {
956                 DEBUG_TRACE (DEBUG::Butler, "auditioner needs butler, call it\n");
957                 _butler->summon ();
958         }
959
960         /* if using a monitor section, run it because otherwise we don't hear anything */
961
962         if (_monitor_out && auditioner->needs_monitor()) {
963                 _monitor_out->monitor_run (_transport_sample, _transport_sample + nframes, nframes, false);
964         }
965
966         /* handle pending events */
967
968         while (pending_events.read (&ev, 1) == 1) {
969                 merge_event (ev);
970         }
971
972         /* if we are not in the middle of a state change,
973            and there are immediate events queued up,
974            process them.
975         */
976
977         while (!non_realtime_work_pending() && !immediate_events.empty()) {
978                 SessionEvent *ev = immediate_events.front ();
979                 immediate_events.pop_front ();
980                 process_event (ev);
981         }
982
983         if (!auditioner->auditioning()) {
984                 /* auditioner no longer active, so go back to the normal process callback */
985                 process_function = &Session::process_with_events;
986         }
987 }
988
989 bool
990 Session::maybe_sync_start (pframes_t & nframes)
991 {
992         pframes_t sync_offset;
993
994         if (!waiting_for_sync_offset) {
995                 return false;
996         }
997
998         if (_engine.get_sync_offset (sync_offset) && sync_offset < nframes) {
999
1000                 /* generate silence up to the sync point, then
1001                    adjust nframes + offset to reflect whatever
1002                    is left to do.
1003                 */
1004
1005                 no_roll (sync_offset);
1006                 nframes -= sync_offset;
1007                 Port::increment_global_port_buffer_offset (sync_offset);
1008                 waiting_for_sync_offset = false;
1009
1010                 if (nframes == 0) {
1011                         return true; // done, nothing left to process
1012                 }
1013
1014         } else {
1015
1016                 /* sync offset point is not within this process()
1017                    cycle, so just generate silence. and don't bother
1018                    with any fancy stuff here, just the minimal silence.
1019                 */
1020
1021                 _silent = true;
1022
1023                 if (Config->get_locate_while_waiting_for_sync()) {
1024                         if (micro_locate (nframes)) {
1025                                 /* XXX ERROR !!! XXX */
1026                         }
1027                 }
1028
1029                 return true; // done, nothing left to process
1030         }
1031
1032         return false;
1033 }
1034
1035 void
1036 Session::queue_event (SessionEvent* ev)
1037 {
1038         if (_state_of_the_state & Deletion) {
1039                 return;
1040         } else if (_state_of_the_state & Loading) {
1041                 merge_event (ev);
1042         } else {
1043                 Glib::Threads::Mutex::Lock lm (rb_write_lock);
1044                 pending_events.write (&ev, 1);
1045         }
1046 }
1047
1048 void
1049 Session::set_next_event ()
1050 {
1051         if (events.empty()) {
1052                 next_event = events.end();
1053                 return;
1054         }
1055
1056         if (next_event == events.end()) {
1057                 next_event = events.begin();
1058         }
1059
1060         if ((*next_event)->action_sample > _transport_sample) {
1061                 next_event = events.begin();
1062         }
1063
1064         for (; next_event != events.end(); ++next_event) {
1065                 if ((*next_event)->action_sample >= _transport_sample) {
1066                         break;
1067                 }
1068         }
1069 }
1070
1071 void
1072 Session::process_event (SessionEvent* ev)
1073 {
1074         bool remove = true;
1075         bool del = true;
1076
1077         /* if we're in the middle of a state change (i.e. waiting
1078            for the butler thread to complete the non-realtime
1079            part of the change), we'll just have to queue this
1080            event for a time when the change is complete.
1081         */
1082
1083         if (non_realtime_work_pending()) {
1084
1085                 /* except locates, which we have the capability to handle */
1086
1087                 if (ev->type != SessionEvent::Locate) {
1088                         immediate_events.insert (immediate_events.end(), ev);
1089                         _remove_event (ev);
1090                         return;
1091                 }
1092         }
1093
1094         DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Processing event: %1 @ %2\n", enum_2_string (ev->type), _transport_sample));
1095
1096         switch (ev->type) {
1097         case SessionEvent::SetLoop:
1098                 set_play_loop (ev->yes_or_no, ev->speed);
1099                 break;
1100
1101         case SessionEvent::AutoLoop:
1102                 if (play_loop) {
1103                         /* roll after locate, do not flush, set "with loop"
1104                            true only if we are seamless looping
1105                         */
1106                         start_locate (ev->target_sample, true, false, Config->get_seamless_loop());
1107                 }
1108                 remove = false;
1109                 del = false;
1110                 break;
1111
1112         case SessionEvent::AutoLoopDeclick:
1113                 if (play_loop) {
1114                         /* Request a declick fade-out and a fade-in; the fade-out will happen
1115                            at the end of the loop, and the fade-in at the start.
1116                         */
1117                         transport_sub_state |= (PendingLoopDeclickOut | PendingLoopDeclickIn);
1118                 }
1119                 remove = false;
1120                 del = false;
1121                 break;
1122
1123         case SessionEvent::Locate:
1124                 if (ev->yes_or_no) { /* force locate */
1125                         /* args: do not roll after locate, do flush, not with loop */
1126                         locate (ev->target_sample, false, true, false);
1127                 } else {
1128                         /* args: do not roll after locate, do flush, not with loop */
1129                         start_locate (ev->target_sample, false, true, false);
1130                 }
1131                 _send_timecode_update = true;
1132                 break;
1133
1134         case SessionEvent::LocateRoll:
1135                 if (ev->yes_or_no) {
1136                         /* args: roll after locate, do flush, not with loop */
1137                         locate (ev->target_sample, true, true, false);
1138                 } else {
1139                         /* args: roll after locate, do flush, not with loop */
1140                         start_locate (ev->target_sample, true, true, false);
1141                 }
1142                 _send_timecode_update = true;
1143                 break;
1144
1145         case SessionEvent::Skip:
1146                 if (Config->get_skip_playback()) {
1147                         start_locate (ev->target_sample, true, true, false);
1148                         _send_timecode_update = true;
1149                 }
1150                 remove = false;
1151                 del = false;
1152                 break;
1153
1154         case SessionEvent::LocateRollLocate:
1155                 // locate is handled by ::request_roll_at_and_return()
1156                 _requested_return_sample = ev->target_sample;
1157                 request_locate (ev->target2_sample, true);
1158                 break;
1159
1160
1161         case SessionEvent::SetTransportSpeed:
1162                 set_transport_speed (ev->speed, ev->target_sample, ev->yes_or_no, ev->second_yes_or_no, ev->third_yes_or_no);
1163                 break;
1164
1165         case SessionEvent::PunchIn:
1166                 // cerr << "PunchIN at " << transport_sample() << endl;
1167                 if (config.get_punch_in() && record_status() == Enabled) {
1168                         enable_record ();
1169                 }
1170                 remove = false;
1171                 del = false;
1172                 break;
1173
1174         case SessionEvent::PunchOut:
1175                 // cerr << "PunchOUT at " << transport_sample() << endl;
1176                 if (config.get_punch_out()) {
1177                         step_back_from_record ();
1178                 }
1179                 remove = false;
1180                 del = false;
1181                 break;
1182
1183         case SessionEvent::StopOnce:
1184                 if (!non_realtime_work_pending()) {
1185                         _clear_event_type (SessionEvent::StopOnce);
1186                         stop_transport (ev->yes_or_no);
1187                 }
1188                 remove = false;
1189                 del = false;
1190                 break;
1191
1192         case SessionEvent::RangeStop:
1193                 if (!non_realtime_work_pending()) {
1194                         stop_transport (ev->yes_or_no);
1195                 }
1196                 remove = false;
1197                 del = false;
1198                 break;
1199
1200         case SessionEvent::RangeLocate:
1201                 /* args: roll after locate, do flush, not with loop */
1202                 start_locate (ev->target_sample, true, true, false);
1203                 remove = false;
1204                 del = false;
1205                 break;
1206
1207         case SessionEvent::Overwrite:
1208                 overwrite_some_buffers (static_cast<Track*>(ev->ptr));
1209                 break;
1210
1211         case SessionEvent::SetSyncSource:
1212                 DEBUG_TRACE (DEBUG::Slave, "seen request for new slave\n");
1213                 use_sync_source (ev->slave);
1214                 break;
1215
1216         case SessionEvent::Audition:
1217                 set_audition (ev->region);
1218                 // drop reference to region
1219                 ev->region.reset ();
1220                 break;
1221
1222         case SessionEvent::SetPlayAudioRange:
1223                 set_play_range (ev->audio_range, (ev->speed == 1.0f));
1224                 break;
1225
1226         case SessionEvent::CancelPlayAudioRange:
1227                 unset_play_range();
1228                 break;
1229
1230         case SessionEvent::RealTimeOperation:
1231                 process_rtop (ev);
1232                 del = false; // other side of RT request needs to clean up
1233                 break;
1234
1235         case SessionEvent::AdjustPlaybackBuffering:
1236                 schedule_playback_buffering_adjustment ();
1237                 break;
1238
1239         case SessionEvent::AdjustCaptureBuffering:
1240                 schedule_capture_buffering_adjustment ();
1241                 break;
1242
1243         case SessionEvent::SetTimecodeTransmission:
1244                 g_atomic_int_set (&_suspend_timecode_transmission, ev->yes_or_no ? 0 : 1);
1245                 break;
1246
1247         default:
1248           fatal << string_compose(_("Programming error: illegal event type in process_event (%1)"), ev->type) << endmsg;
1249                 abort(); /*NOTREACHED*/
1250                 break;
1251         };
1252
1253         if (remove) {
1254                 del = del && !_remove_event (ev);
1255         }
1256
1257         if (del) {
1258                 delete ev;
1259         }
1260 }
1261
1262 samplepos_t
1263 Session::compute_stop_limit () const
1264 {
1265         if (!Config->get_stop_at_session_end ()) {
1266                 return max_samplepos;
1267         }
1268
1269         if (_slave) {
1270                 return max_samplepos;
1271         }
1272
1273         bool const punching_in = (config.get_punch_in () && _locations->auto_punch_location());
1274         bool const punching_out = (config.get_punch_out () && _locations->auto_punch_location());
1275
1276         if (actively_recording ()) {
1277                 /* permanently recording */
1278                 return max_samplepos;
1279         } else if (punching_in && !punching_out) {
1280                 /* punching in but never out */
1281                 return max_samplepos;
1282         } else if (punching_in && punching_out && _locations->auto_punch_location()->end() > current_end_sample()) {
1283                 /* punching in and punching out after session end */
1284                 return max_samplepos;
1285         }
1286
1287         return current_end_sample ();
1288 }
1289
1290
1291
1292 /* dedicated thread for signal emission.
1293  *
1294  * while sending cross-thread signals from the process thread
1295  * is fine in general, PBD::Signal's use of boost::function and
1296  * boost:bind can produce a vast overhead which is not
1297  * acceptable for low latency.
1298  *
1299  * This works around the issue by moving the boost overhead
1300  * out of the RT thread. The overall load is probably higher but
1301  * the realtime thread remains unaffected.
1302  */
1303
1304 void
1305 Session::emit_route_signals ()
1306 {
1307         // TODO use RAII to allow using these signals in other places
1308         BatchUpdateStart(); /* EMIT SIGNAL */
1309         boost::shared_ptr<RouteList> r = routes.reader ();
1310         for (RouteList::const_iterator ci = r->begin(); ci != r->end(); ++ci) {
1311                 (*ci)->emit_pending_signals ();
1312         }
1313         BatchUpdateEnd(); /* EMIT SIGNAL */
1314 }
1315
1316 void
1317 Session::emit_thread_start ()
1318 {
1319         if (_rt_thread_active) {
1320                 return;
1321         }
1322         _rt_thread_active = true;
1323
1324         if (pthread_create (&_rt_emit_thread, NULL, emit_thread, this)) {
1325                 _rt_thread_active = false;
1326         }
1327 }
1328
1329 void
1330 Session::emit_thread_terminate ()
1331 {
1332         if (!_rt_thread_active) {
1333                 return;
1334         }
1335         _rt_thread_active = false;
1336
1337         if (pthread_mutex_lock (&_rt_emit_mutex) == 0) {
1338                 pthread_cond_signal (&_rt_emit_cond);
1339                 pthread_mutex_unlock (&_rt_emit_mutex);
1340         }
1341
1342         void *status;
1343         pthread_join (_rt_emit_thread, &status);
1344 }
1345
1346 void *
1347 Session::emit_thread (void *arg)
1348 {
1349         Session *s = static_cast<Session *>(arg);
1350         s->emit_thread_run ();
1351         pthread_exit (0);
1352         return 0;
1353 }
1354
1355 void
1356 Session::emit_thread_run ()
1357 {
1358         pthread_mutex_lock (&_rt_emit_mutex);
1359         while (_rt_thread_active) {
1360                 emit_route_signals();
1361                 pthread_cond_wait (&_rt_emit_cond, &_rt_emit_mutex);
1362         }
1363         pthread_mutex_unlock (&_rt_emit_mutex);
1364 }