a) moved metering and meter falloff code into libardour
[ardour.git] / libs / ardour / session_butler.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 <algorithm>
22 #include <string>
23 #include <cmath>
24 #include <cerrno>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <poll.h>
28
29 #include <pbd/error.h>
30 #include <pbd/lockmonitor.h>
31 #include <pbd/pthread_utils.h>
32
33 #include <ardour/configuration.h>
34 #include <ardour/audioengine.h>
35 #include <ardour/session.h>
36 #include <ardour/diskstream.h>
37 #include <ardour/crossfade.h>
38 #include <ardour/timestamps.h>
39
40 #include "i18n.h"
41
42 using namespace std;
43 using namespace ARDOUR;
44 //using namespace sigc;
45
46 static float _read_data_rate;
47 static float _write_data_rate;
48
49 /* XXX put this in the right place */
50
51 static inline uint32_t next_power_of_two (uint32_t n)
52 {
53         --n;
54         n |= n >> 16;
55         n |= n >> 8;
56         n |= n >> 4;
57         n |= n >> 2;
58         n |= n >> 1;
59         ++n;
60         return n;
61 }
62
63 /*---------------------------------------------------------------------------
64  BUTLER THREAD 
65  ---------------------------------------------------------------------------*/
66
67 int
68 Session::start_butler_thread ()
69 {
70         /* size is in Samples, not bytes */
71
72         dstream_buffer_size = (uint32_t) floor (Config->get_track_buffer_seconds() * (float) frame_rate());
73
74         Crossfade::set_buffer_size (dstream_buffer_size);
75
76         pthread_cond_init (&butler_paused, 0);
77         
78         butler_should_run = false;
79
80         if (pipe (butler_request_pipe)) {
81                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
82                 return -1;
83         }
84
85         if (fcntl (butler_request_pipe[0], F_SETFL, O_NONBLOCK)) {
86                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
87                 return -1;
88         }
89
90         if (fcntl (butler_request_pipe[1], F_SETFL, O_NONBLOCK)) {
91                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
92                 return -1;
93         }
94
95         if (pthread_create_and_store ("disk butler", &butler_thread, 0, _butler_thread_work, this)) {
96                 error << _("Session: could not create butler thread") << endmsg;
97                 return -1;
98         }
99
100         // pthread_detach (butler_thread);
101
102         return 0;
103 }
104
105 void
106 Session::terminate_butler_thread ()
107 {
108         void* status;
109         char c = ButlerRequest::Quit;
110         ::write (butler_request_pipe[1], &c, 1);
111         pthread_join (butler_thread, &status);
112 }
113
114 void
115 Session::schedule_butler_transport_work ()
116 {
117         atomic_inc (&butler_should_do_transport_work);
118         summon_butler ();
119 }
120
121 void
122 Session::schedule_curve_reallocation ()
123 {
124         post_transport_work = PostTransportWork (post_transport_work | PostTransportCurveRealloc);
125         schedule_butler_transport_work ();
126 }
127
128 void
129 Session::summon_butler ()
130 {
131         char c = ButlerRequest::Run;
132         ::write (butler_request_pipe[1], &c, 1);
133 }
134
135 void
136 Session::stop_butler ()
137 {
138         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
139         char c = ButlerRequest::Pause;
140         ::write (butler_request_pipe[1], &c, 1);
141         pthread_cond_wait (&butler_paused, butler_request_lock.mutex());
142 }
143
144 void
145 Session::wait_till_butler_finished ()
146 {
147         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
148         char c = ButlerRequest::Wake;
149         ::write (butler_request_pipe[1], &c, 1);
150         pthread_cond_wait (&butler_paused, butler_request_lock.mutex());
151 }
152
153 void *
154 Session::_butler_thread_work (void* arg)
155 {
156         PBD::ThreadCreated (pthread_self(), X_("Butler"));
157         return ((Session *) arg)->butler_thread_work ();
158         return 0;
159 }
160
161 #define transport_work_requested() atomic_read(&butler_should_do_transport_work)
162
163 void *
164 Session::butler_thread_work ()
165 {
166         uint32_t err = 0;
167         int32_t bytes;
168         bool compute_io;
169         struct timeval begin, end;
170         struct pollfd pfd[1];
171         bool disk_work_outstanding = false;
172         DiskStreamList::iterator i;
173
174         butler_mixdown_buffer = new Sample[DiskStream::disk_io_frames()];
175         butler_gain_buffer = new gain_t[DiskStream::disk_io_frames()];
176         // this buffer is used for temp conversion purposes in filesources
177         char * conv_buffer = conversion_buffer(ButlerContext);
178
179         while (true) {
180
181                 pfd[0].fd = butler_request_pipe[0];
182                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
183                 
184                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
185                         
186                         if (errno == EINTR) {
187                                 continue;
188                         }
189                         
190                         error << string_compose (_("poll on butler request pipe failed (%1)"),
191                                           strerror (errno))
192                               << endmsg;
193                         break;
194                 }
195
196                 if (pfd[0].revents & ~POLLIN) {
197                         error << _("Error on butler thread request pipe") << endmsg;
198                         break;
199                 }
200                 
201                 if (pfd[0].revents & POLLIN) {
202                         
203                         char req;
204                         
205                         /* empty the pipe of all current requests */
206                         
207                         while (1) {
208                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
209                                 
210                                 if (nread == 1) {
211                                         
212                                         switch ((ButlerRequest::Type) req) {
213                                                 
214                                         case ButlerRequest::Wake:
215                                                 break;
216
217                                         case ButlerRequest::Run:
218                                                 butler_should_run = true;
219                                                 break;
220                                                 
221                                         case ButlerRequest::Pause:
222                                                 butler_should_run = false;
223                                                 break;
224                                                 
225                                         case ButlerRequest::Quit:
226                                                 pthread_exit_pbd (0);
227                                                 /*NOTREACHED*/
228                                                 break;
229                                                 
230                                         default:
231                                                 break;
232                                         }
233                                         
234                                 } else if (nread == 0) {
235                                         break;
236                                 } else if (errno == EAGAIN) {
237                                         break;
238                                 } else {
239                                         fatal << _("Error reading from butler request pipe") << endmsg;
240                                         /*NOTREACHED*/
241                                 }
242                         }
243                 }
244         
245                 for (i = diskstreams.begin(); i != diskstreams.end(); ++i) {
246                         // cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
247                 }
248
249                 if (transport_work_requested()) {
250                         butler_transport_work ();
251                 }
252
253                 disk_work_outstanding = false;
254                 bytes = 0;
255                 compute_io = true;
256
257                 gettimeofday (&begin, 0);
258
259                 RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
260                 
261                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
262                         
263                         // cerr << "rah fondr " << (*i)->io()->name () << endl;
264
265                         switch ((*i)->do_refill (butler_mixdown_buffer, butler_gain_buffer, conv_buffer)) {
266                         case 0:
267                                 bytes += (*i)->read_data_count();
268                                 break;
269                         case 1:
270                                 bytes += (*i)->read_data_count();
271                                 disk_work_outstanding = true;
272                                 break;
273                                 
274                         default:
275                                 compute_io = false;
276                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
277                                 break;
278                         }
279
280                 }
281
282                 if (i != diskstreams.end()) {
283                         /* we didn't get to all the streams */
284                         disk_work_outstanding = true;
285                 }
286                 
287                 if (!err && transport_work_requested()) {
288                         continue;
289                 }
290
291                 if (compute_io) {
292                         gettimeofday (&end, 0);
293                         
294                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
295                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
296                         
297                         _read_data_rate = bytes / (e - b);
298                 }
299
300                 bytes = 0;
301                 compute_io = true;
302                 gettimeofday (&begin, 0);
303                 
304                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
305                         
306                         // cerr << "write behind for " << (*i)->name () << endl;
307                         
308                         switch ((*i)->do_flush (conv_buffer)) {
309                         case 0:
310                                 bytes += (*i)->write_data_count();
311                                 break;
312                         case 1:
313                                 bytes += (*i)->write_data_count();
314                                 disk_work_outstanding = true;
315                                 break;
316                                 
317                         default:
318                                 err++;
319                                 compute_io = false;
320                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
321                                 /* don't break - try to flush all streams in case they 
322                                    are split across disks.
323                                 */
324                         }
325                 }
326
327                 if (err && actively_recording()) {
328                         /* stop the transport and try to catch as much possible
329                            captured state as we can.
330                         */
331                         request_stop ();
332                 }
333
334                 if (i != diskstreams.end()) {
335                         /* we didn't get to all the streams */
336                         disk_work_outstanding = true;
337                 }
338                 
339                 if (!err && transport_work_requested()) {
340                         continue;
341                 }
342
343                 if (compute_io) {
344                         gettimeofday (&end, 0);
345                         
346                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
347                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
348                         
349                         _write_data_rate = bytes / (e - b);
350                 }
351                 
352                 if (!disk_work_outstanding) {
353                         refresh_disk_space ();
354                 }
355
356
357                 {
358                         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
359
360                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
361 //                              for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
362 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
363 //                              }
364
365                                 continue;
366                         }
367
368                         pthread_cond_signal (&butler_paused);
369                 }
370         }
371
372         pthread_exit_pbd (0);
373         /*NOTREACHED*/
374         return (0);
375 }
376
377
378 void
379 Session::request_overwrite_buffer (DiskStream* stream)
380 {
381         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
382         ev->set_ptr (stream);
383         queue_event (ev);
384 }
385
386 void
387 Session::overwrite_some_buffers (DiskStream* ds)
388 {
389         /* executed by the audio thread */
390
391         if (actively_recording()) {
392                 return;
393         }
394
395         if (ds) {
396
397                 ds->set_pending_overwrite (true);
398
399         } else {
400
401                 RWLockMonitor dm (diskstream_lock, false, __LINE__, __FILE__);
402                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
403                         (*i)->set_pending_overwrite (true);
404                 }
405         }
406
407         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
408         schedule_butler_transport_work ();
409 }
410
411 float
412 Session::read_data_rate () const
413 {
414         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
415            in action. ignore it.
416         */
417         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
418 }
419
420 float
421 Session::write_data_rate () const
422 {
423         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
424            in action. ignore it.
425         */
426         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
427 }
428
429 uint32_t
430 Session::playback_load ()
431 {
432         return (uint32_t) atomic_read (&_playback_load);
433 }
434
435 uint32_t
436 Session::capture_load ()
437 {
438         return (uint32_t) atomic_read (&_capture_load);
439 }
440
441 uint32_t
442 Session::playback_load_min ()
443 {
444         return (uint32_t) atomic_read (&_playback_load_min);
445 }
446
447 uint32_t
448 Session::capture_load_min ()
449 {
450         return (uint32_t) atomic_read (&_capture_load_min);
451 }
452
453 void
454 Session::reset_capture_load_min ()
455 {
456         atomic_set (&_capture_load_min, 100);
457 }
458
459
460 void
461 Session::reset_playback_load_min ()
462 {
463         atomic_set (&_playback_load_min, 100);
464 }