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