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