3280a5f4bb49ec81940e2580be30dfc5771f3c7d
[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     $Id$
19 */
20
21 #include <cmath>
22 #include <cerrno>
23 #include <algorithm>
24 #include <unistd.h>
25
26 #include <ardour/timestamps.h>
27
28 #include <pbd/error.h>
29 #include <pbd/atomic.h>
30 #include <pbd/lockmonitor.h>
31
32 #include <ardour/ardour.h>
33 #include <ardour/session.h>
34 #include <ardour/diskstream.h>
35 #include <ardour/audioengine.h>
36 #include <ardour/slave.h>
37 #include <ardour/auditioner.h>
38 #include <ardour/cycles.h>
39 #include <ardour/cycle_timer.h>
40
41 #include "i18n.h"
42
43 using namespace ARDOUR;
44 //using namespace sigc;
45 using namespace std;
46
47 void
48 Session::process (jack_nframes_t nframes)
49 {
50         if (synced_to_jack() && waiting_to_start) {
51                 if ( _engine.transport_state() == AudioEngine::TransportRolling) {
52                         actually_start_transport ();
53                 }
54         }
55
56         if (non_realtime_work_pending()) {
57                 if (atomic_read (&butler_should_do_transport_work) == 0) {
58                         post_transport ();
59                 } 
60         } 
61         
62         (this->*process_function) (nframes);
63 }
64
65 void
66 Session::prepare_diskstreams ()
67 {
68         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
69                 (*i)->prepare ();
70         }
71 }
72
73 int
74 Session::no_roll (jack_nframes_t nframes, jack_nframes_t offset)
75 {
76         jack_nframes_t end_frame = _transport_frame + nframes;
77         int ret = 0;
78         bool declick = get_transport_declick_required();
79
80         if (_click_io) {
81                 _click_io->silence (nframes, offset);
82         }
83
84         /* XXX we're supposed to have the route_lock while doing this.
85            this is really bad ...
86         */
87
88         if (atomic_read (&processing_prohibited)) {
89                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
90                         (*i)->silence (nframes, offset);
91                 }
92                 return 0;
93         }
94
95         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
96                 
97                 if ((*i)->hidden()) {
98                         continue;
99                 }
100                 
101                 (*i)->set_pending_declick (declick);
102                 
103                 if ((*i)->no_roll (nframes, _transport_frame, end_frame, offset, non_realtime_work_pending(), 
104                                    actively_recording(), declick)) {
105                         error << string_compose(_("Session: error in no roll for %1"), (*i)->name()) << endmsg;
106                         ret = -1;
107                         break;
108                 }
109         }
110
111         return ret;
112 }
113
114 int
115 Session::process_routes (jack_nframes_t nframes, jack_nframes_t offset)
116 {
117         bool record_active;
118         int  declick = get_transport_declick_required();
119         bool rec_monitors = get_rec_monitors_input();
120
121         if (transport_sub_state & StopPendingCapture) {
122                 /* force a declick out */
123                 declick = -1;
124         }
125
126         record_active = actively_recording(); // || (get_record_enabled() && get_punch_in());
127
128         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
129
130                 int ret;
131
132                 if ((*i)->hidden()) {
133                         continue;
134                 }
135
136                 (*i)->set_pending_declick (declick);
137
138                 if ((ret = (*i)->roll (nframes, _transport_frame, _transport_frame + nframes, offset, declick, record_active, rec_monitors)) < 0) {
139
140                         /* we have to do this here. Route::roll() for an AudioTrack will have called DiskStream::process(),
141                            and the DS will expect DiskStream::commit() to be called. but we're aborting from that
142                            call path, so make sure we release any outstanding locks here before we return failure.
143                         */
144
145                         for (DiskStreamList::iterator ids = diskstreams.begin(); ids != diskstreams.end(); ++ids) {
146                                 (*ids)->recover ();
147                         }
148
149                         stop_transport ();
150                         return -1;
151                 } 
152         }
153
154         return 0;
155 }
156
157 int
158 Session::silent_process_routes (jack_nframes_t nframes, jack_nframes_t offset)
159 {
160         bool record_active = actively_recording();
161         int  declick = get_transport_declick_required();
162         bool rec_monitors = get_rec_monitors_input();
163
164         if (transport_sub_state & StopPendingCapture) {
165                 /* force a declick out */
166                 declick = -1;
167         }
168
169         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
170
171                 int ret;
172
173                 if ((*i)->hidden()) {
174                         continue;
175                 }
176
177                 if ((ret = (*i)->silent_roll (nframes, _transport_frame, _transport_frame + nframes, offset, record_active, rec_monitors)) < 0) {
178                         
179                         /* we have to do this here. Route::roll() for an AudioTrack will have called DiskStream::process(),
180                            and the DS will expect DiskStream::commit() to be called. but we're aborting from that
181                            call path, so make sure we release any outstanding locks here before we return failure.
182                         */
183
184                         for (DiskStreamList::iterator ids = diskstreams.begin(); ids != diskstreams.end(); ++ids) {
185                                 (*ids)->recover ();
186                         }
187
188                         stop_transport ();
189                         return -1;
190                 } 
191         }
192
193         return 0;
194 }
195
196 void
197 Session::commit_diskstreams (jack_nframes_t nframes, bool &needs_butler)
198 {
199         int dret;
200         float pworst = 1.0f;
201         float cworst = 1.0f;
202
203         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
204
205                 if ((*i)->hidden()) {
206                         continue;
207                 }
208                 
209                 /* force all diskstreams not handled by a Route to call do their stuff.
210                  */
211
212                 if ((dret = (*i)->process (_transport_frame, nframes, 0, actively_recording(), get_rec_monitors_input())) == 0) {
213                         if ((*i)->commit (nframes)) {
214                                 needs_butler = true;
215                         }
216
217                 } else if (dret < 0) {
218                         (*i)->recover();
219                 }
220                 
221                 pworst = min (pworst, (*i)->playback_buffer_load());
222                 cworst = min (cworst, (*i)->capture_buffer_load());
223         }
224
225         uint32_t pmin = atomic_read (&_playback_load);
226         uint32_t pminold = atomic_read (&_playback_load_min);
227         uint32_t cmin = atomic_read (&_capture_load);
228         uint32_t cminold = atomic_read (&_capture_load_min);
229
230         atomic_set (&_playback_load, (uint32_t) floor (pworst * 100.0f));
231         atomic_set (&_capture_load, (uint32_t) floor (cworst * 100.0f));
232         atomic_set (&_playback_load_min, min (pmin, pminold));
233         atomic_set (&_capture_load_min, min (cmin, cminold));
234
235         if (actively_recording()) {
236                 set_dirty();
237         }
238 }
239
240 void
241 Session::process_with_events (jack_nframes_t nframes)
242 {
243         Event* ev;
244         jack_nframes_t this_nframes;
245         jack_nframes_t end_frame;
246         jack_nframes_t offset;
247         bool session_needs_butler = false;
248         jack_nframes_t stop_limit;
249         long           frames_moved;
250
251         if (auditioner) {
252                 auditioner->silence (nframes, 0);
253         }
254
255         while (pending_events.read (&ev, 1) == 1) {
256                 merge_event (ev);
257         }
258
259         /* if we are not in the middle of a state change,
260            and there are immediate events queued up,
261            process them. 
262         */
263
264         while (!non_realtime_work_pending() && !immediate_events.empty()) {
265                 Event *ev = immediate_events.front ();
266                 immediate_events.pop_front ();
267                 process_event (ev);
268         }
269
270         if (!process_can_proceed()) {
271                 no_roll (nframes, 0);
272                 return;
273         }
274                 
275         if (events.empty() || next_event == events.end()) {
276                 process_without_events (nframes);
277                 return;
278         }
279
280         end_frame = _transport_frame + nframes;
281
282         {
283                 TentativeRWLockMonitor rm (route_lock, false, __LINE__, __FILE__);
284                 TentativeRWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
285         
286                 Event* this_event;
287                 Events::iterator the_next_one;
288
289                 if (!rm.locked() || !dsm.locked() || (post_transport_work & (PostTransportLocate|PostTransportStop))) {
290                         no_roll (nframes, 0);
291                         return;
292                 }
293                 
294                 if (!_exporting && _slave) {
295                         if (!follow_slave (nframes, 0)) {
296                                 return;
297                         }
298                 } 
299
300                 if (_transport_speed == 0) {
301                         no_roll (nframes, 0);
302                         return;
303                 }
304
305                 if (actively_recording()) {
306                         stop_limit = max_frames;
307                 } else {
308
309                         if (Config->get_stop_at_session_end()) {
310                                 stop_limit = current_end_frame();
311                         } else {
312                                 stop_limit = max_frames;
313                         }
314                 }
315
316                 if (maybe_stop (stop_limit)) {
317                         no_roll (nframes, 0);
318                         return;
319                 } 
320
321                 this_event = *next_event;
322                 the_next_one = next_event;
323                 ++the_next_one;
324
325                 offset = 0;
326
327                 while (nframes) {
328
329                         if (this_event == 0 || this_event->action_frame > end_frame || this_event->action_frame < _transport_frame) {
330
331                                 this_nframes = nframes;
332                                 
333                         } else {
334                                 
335                                 /* compute nframes to next event */
336
337                                 if (this_event->action_frame < end_frame) {
338                                         this_nframes = nframes - (end_frame - this_event->action_frame);
339                                 } else {
340                                         this_nframes = nframes;
341                                 }
342                         }
343
344                         if (this_nframes) {
345                                 
346                                 click (_transport_frame, nframes, offset);
347                                 
348                                 /* now process frames between now and the first event in this block */
349                                 prepare_diskstreams ();
350
351                                 if (process_routes (this_nframes, offset)) {
352                                         no_roll (nframes, 0);
353                                         return;
354                                 }
355                                 
356                                 commit_diskstreams (this_nframes, session_needs_butler);
357
358                                 nframes -= this_nframes;
359                                 offset += this_nframes;
360                                 
361                                 frames_moved = (jack_nframes_t) floor (_transport_speed * this_nframes);
362                         
363                                 if (frames_moved < 0) {
364                                         decrement_transport_position (-frames_moved);
365                                 } else {
366                                         increment_transport_position (frames_moved);
367                                 }
368
369                                 maybe_stop (stop_limit);
370                                 check_declick_out ();
371                         }
372
373                         /* now handle this event and all others scheduled for the same time */
374                         
375                         while (this_event && this_event->action_frame == _transport_frame) {
376                                 process_event (this_event);
377
378                                 if (the_next_one == events.end()) {
379                                         this_event = 0;
380                                 } else {
381                                         this_event = *the_next_one;
382                                         ++the_next_one;
383                                 }
384                         } 
385
386                         /* if an event left our state changing, do the right thing */
387
388                         if (non_realtime_work_pending()) {
389                                 no_roll (nframes, offset);
390                                 break;
391                         }
392
393                         /* this is necessary to handle the case of seamless looping */
394                         /* not sure if it will work in conjuction with varispeed */
395                         end_frame = _transport_frame + nframes;
396                         
397                 }
398
399                 set_next_event ();
400
401         } /* implicit release of route lock */
402
403
404         if (session_needs_butler) {
405                 summon_butler ();
406         } 
407         
408         if (!_engine.freewheeling() && send_mtc) {
409                 send_midi_time_code_in_another_thread ();
410         }
411
412         return;
413 }               
414
415 void
416 Session::reset_slave_state ()
417 {
418         average_slave_delta = 1800;
419         delta_accumulator_cnt = 0;
420         have_first_delta_accumulator = false;
421         slave_state = Stopped;
422 }
423
424 bool
425 Session::transport_locked () const
426 {
427         Slave* sl = _slave;
428
429         if (!locate_pending() && ((_slave_type == None) || (sl && sl->ok() && sl->locked()))) {
430                 return true;
431         }
432
433         return false;
434 }
435
436 bool
437 Session::follow_slave (jack_nframes_t nframes, jack_nframes_t offset)
438 {
439         float slave_speed;
440         jack_nframes_t slave_transport_frame;
441         jack_nframes_t this_delta;
442         int dir;
443         bool starting;
444
445         if (!_slave->ok()) {
446                 stop_transport ();
447                 set_slave_source (None, 0);
448                 goto noroll;
449         }
450         
451         _slave->speed_and_position (slave_speed, slave_transport_frame);
452
453         if (!_slave->locked()) {
454                 goto noroll;
455         }
456
457         if (slave_transport_frame > _transport_frame) {
458                 this_delta = slave_transport_frame - _transport_frame;
459                 dir = 1;
460         } else {
461                 this_delta = _transport_frame - slave_transport_frame;
462                 dir = -1;
463         }
464
465         if ((starting = _slave->starting())) {
466                 slave_speed = 0.0f;
467         }
468
469 #if 0
470         cerr << "delta = " << (int) (dir * this_delta)
471              << " speed = " << slave_speed 
472              << " ts = " << _transport_speed 
473              << " M@"<< slave_transport_frame << " S@" << _transport_frame 
474              << " avgdelta = " << average_slave_delta 
475              << endl;
476 #endif  
477
478         if (Config->get_timecode_source_is_synced()) {
479
480                 /* if the TC source is synced, then we assume that its 
481                    speed is binary: 0.0 or 1.0
482                 */
483
484                 if (slave_speed != 0.0f) {
485                         slave_speed = 1.0f;
486                 } 
487
488         } else {
489
490                 /* TC source is able to drift relative to us (slave)
491                    so we need to keep track of the drift and adjust
492                    our speed to remain locked.
493                 */
494
495                 if (delta_accumulator_cnt >= delta_accumulator_size) {
496                         have_first_delta_accumulator = true;
497                         delta_accumulator_cnt = 0;
498                 }
499
500                 if (delta_accumulator_cnt != 0 || this_delta < _current_frame_rate) {
501                         delta_accumulator[delta_accumulator_cnt++] = dir*this_delta;
502                 }
503                 
504                 if (have_first_delta_accumulator) {
505                         average_slave_delta = 0;
506                         for (int i = 0; i < delta_accumulator_size; ++i) {
507                                 average_slave_delta += delta_accumulator[i];
508                         }
509                         average_slave_delta /= delta_accumulator_size;
510                         if (average_slave_delta < 0) {
511                                 average_dir = -1;
512                                 average_slave_delta = -average_slave_delta;
513                         } else {
514                                 average_dir = 1;
515                         }
516                         // cerr << "avgdelta = " << average_slave_delta*average_dir << endl;
517                 }
518         }
519
520         if (slave_speed != 0.0f) {
521
522                 /* slave is running */
523
524                 switch (slave_state) {
525                 case Stopped:
526                         if (_slave->requires_seekahead()) {
527                                 slave_wait_end = slave_transport_frame + _current_frame_rate;
528                                 locate (slave_wait_end, false, false);
529                                 slave_state = Waiting;
530                                 starting = true;
531
532                         } else {
533
534                                 slave_state = Running;
535
536                                 Location* al = _locations.auto_loop_location();
537
538                                 if (al && auto_loop && (slave_transport_frame < al->start() || slave_transport_frame > al->end())) {
539                                         // cancel looping
540                                         request_auto_loop(false);
541                                 }
542
543                                 if (slave_transport_frame != _transport_frame) {
544                                         locate (slave_transport_frame, false, false);
545                                 }
546                         }
547                         break;
548
549                 case Waiting:
550                         break;
551
552                 default:
553                         break;
554
555                 }
556
557                 if (slave_state == Waiting) {
558
559                         // cerr << "waiting at " << slave_transport_frame << endl;
560                         TentativeRWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
561                                 
562                         if (dsm.locked() && slave_transport_frame >= slave_wait_end) {
563                                 // cerr << "\tstart at " << _transport_frame << endl;
564
565                                 slave_state = Running;
566
567                                 bool ok = true;
568                                 jack_nframes_t frame_delta = slave_transport_frame - _transport_frame;
569                                 
570                                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
571                                         if (!(*i)->can_internal_playback_seek (frame_delta)) {
572                                                 ok = false;
573                                                 break;
574                                         }
575                                 }
576
577                                 if (ok) {
578                                         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
579                                                 (*i)->internal_playback_seek (frame_delta);
580                                         }
581                                         _transport_frame += frame_delta;
582                                        
583                                 } else {
584                                         // cerr << "cannot micro-seek\n";
585                                         /* XXX what? */
586                                 }
587
588                                 memset (delta_accumulator, 0, sizeof (jack_nframes_t) * delta_accumulator_size);
589                                 average_slave_delta = 0;
590                                 this_delta = 0;
591                         }
592                 }
593                 
594                 if (slave_state == Running && _transport_speed == 0.0f) {
595                         
596                         // cerr << "slave starts transport\n";
597                         
598                         start_transport ();
599                 } 
600
601         } else {
602
603                 /* slave has stopped */
604
605                 if (_transport_speed != 0.0f) {
606
607                         // cerr << "slave stops transport: " << slave_speed << " frame: " << slave_transport_frame 
608                         // << " tf = " << _transport_frame
609                         // << endl;
610                         
611                         if (_slave_type == JACK) {
612                                 last_stop_frame = _transport_frame;
613                         }
614
615                         stop_transport();
616                 }
617
618                 if (slave_transport_frame != _transport_frame) {
619                         // cerr << "slave stopped, move to " << slave_transport_frame << endl;
620                         force_locate (slave_transport_frame, false);
621                 }
622
623                 slave_state = Stopped;
624         }
625
626         if (slave_state == Running && !Config->get_timecode_source_is_synced()) {
627
628
629                 if (_transport_speed != 0.0f) {
630                         
631                         /* 
632                            note that average_dir is +1 or -1 
633                         */
634                         
635                         const float adjust_seconds = 1.0f;
636                         float delta;
637
638                         //if (average_slave_delta == 0) {
639                                 delta = this_delta;
640                                 delta *= dir;
641 //                      } else {
642 //                              delta = average_slave_delta;
643 //                              delta *= average_dir;
644 //                      }
645
646                         float adjusted_speed = slave_speed +
647                                 (delta / (adjust_seconds * _current_frame_rate));
648                         
649                         // cerr << "adjust using " << delta
650                         // << " towards " << adjusted_speed
651                         // << " ratio = " << adjusted_speed / slave_speed
652                         // << " current = " << _transport_speed
653                         // << " slave @ " << slave_speed
654                         // << endl;
655                         
656                         request_transport_speed (adjusted_speed);
657                         
658 #if 1
659                         if ((jack_nframes_t) average_slave_delta > _slave->resolution()) {
660                                 // cerr << "not locked\n";
661                                 goto silent_motion;
662                         }
663 #endif
664                 }
665         } 
666
667         if (!starting && !non_realtime_work_pending()) {
668                 /* speed is set, we're locked, and good to go */
669                 return true;
670         }
671
672   silent_motion:
673
674         if (slave_speed && _transport_speed) {
675
676                 /* something isn't right, but we should move with the master
677                    for now.
678                 */
679
680                 bool need_butler;
681                 
682                 TentativeRWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
683                 if (!dsm.locked()) {
684                         goto noroll;
685                 }
686
687                 
688                 prepare_diskstreams ();
689                 silent_process_routes (nframes, offset);
690                 commit_diskstreams (nframes, need_butler);
691
692                 if (need_butler) {
693                         summon_butler ();
694                 }
695                 
696                 jack_nframes_t frames_moved = (long) floor (_transport_speed * nframes);
697                 
698                 if (frames_moved < 0) {
699                         decrement_transport_position (-frames_moved);
700                 } else {
701                         increment_transport_position (frames_moved);
702                 }
703                 
704                 jack_nframes_t stop_limit;
705                 
706                 if (actively_recording()) {
707                         stop_limit = max_frames;
708                 } else {
709                         if (Config->get_stop_at_session_end()) {
710                                 stop_limit = current_end_frame();
711                         } else {
712                                 stop_limit = max_frames;
713                         }
714                 }
715
716                 maybe_stop (stop_limit);
717         }
718
719   noroll:
720         /* don't move at all */
721         no_roll (nframes, 0);
722         return false;
723 }
724
725 void
726 Session::process_without_events (jack_nframes_t nframes)
727 {
728         bool session_needs_butler = false;
729         jack_nframes_t stop_limit;
730         long frames_moved;
731         
732         {
733                 TentativeRWLockMonitor rm (route_lock, false, __LINE__, __FILE__);
734                 TentativeRWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
735
736                 if (!rm.locked() || !dsm.locked() || (post_transport_work & (PostTransportLocate|PostTransportStop))) {
737                         no_roll (nframes, 0);
738                         return;
739                 }
740
741                 if (!_exporting && _slave) {
742                         if (!follow_slave (nframes, 0)) {
743                                 return;
744                         }
745                 } 
746
747                 if (_transport_speed == 0) {
748                         no_roll (nframes, 0);
749                         return;
750                 }
751                 
752                 if (actively_recording()) {
753                         stop_limit = max_frames;
754                 } else {
755                         if (Config->get_stop_at_session_end()) {
756                                 stop_limit = current_end_frame();
757                         } else {
758                                 stop_limit = max_frames;
759                         }
760                 }
761                 
762                 if (maybe_stop (stop_limit)) {
763                         no_roll (nframes, 0);
764                         return;
765                 } 
766
767                 click (_transport_frame, nframes, 0);
768
769                 prepare_diskstreams ();
770         
771                 frames_moved = (long) floor (_transport_speed * nframes);
772
773                 if (process_routes (nframes, 0)) {
774                         no_roll (nframes, 0);
775                         return;
776                 }
777
778                 commit_diskstreams (nframes, session_needs_butler);
779
780                 if (frames_moved < 0) {
781                         decrement_transport_position (-frames_moved);
782                 } else {
783                         increment_transport_position (frames_moved);
784                 }
785                 
786                 maybe_stop (stop_limit);
787                 check_declick_out ();
788
789         } /* implicit release of route lock */
790
791         if (session_needs_butler) {
792                 summon_butler ();
793         } 
794         
795         if (!_engine.freewheeling() && send_mtc) {
796                 send_midi_time_code_in_another_thread ();
797         }
798
799         return;
800 }               
801
802 void
803 Session::process_audition (jack_nframes_t nframes)
804 {
805         TentativeRWLockMonitor rm (route_lock, false, __LINE__, __FILE__);
806         Event* ev;
807
808         if (rm.locked()) {
809                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
810                         if (!(*i)->hidden()) {
811                                 (*i)->silence (nframes, 0);
812                         }
813                 }
814         }
815         
816         if (auditioner->play_audition (nframes) > 0) {
817                 summon_butler ();
818         } 
819
820         while (pending_events.read (&ev, 1) == 1) {
821                 merge_event (ev);
822         }
823
824         /* if we are not in the middle of a state change,
825            and there are immediate events queued up,
826            process them. 
827         */
828
829         while (!non_realtime_work_pending() && !immediate_events.empty()) {
830                 Event *ev = immediate_events.front ();
831                 immediate_events.pop_front ();
832                 process_event (ev);
833         }
834
835         if (!auditioner->active()) {
836                 process_function = &Session::process_with_events;
837         }
838 }
839