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