committed RWlock fixes to libardour. added hw monitoring fixes from nick_m. minor...
[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() * (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
158         return ((Session *) arg)->butler_thread_work ();
159         return 0;
160 }
161
162 #define transport_work_requested() atomic_read(&butler_should_do_transport_work)
163
164 void *
165 Session::butler_thread_work ()
166 {
167         uint32_t err = 0;
168         int32_t bytes;
169         bool compute_io;
170         struct timeval begin, end;
171         struct pollfd pfd[1];
172         bool disk_work_outstanding = false;
173         DiskStreamList::iterator i;
174
175         butler_mixdown_buffer = new Sample[DiskStream::disk_io_frames()];
176         butler_gain_buffer = new gain_t[DiskStream::disk_io_frames()];
177
178         while (true) {
179
180                 pfd[0].fd = butler_request_pipe[0];
181                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
182                 
183                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
184                         
185                         if (errno == EINTR) {
186                                 continue;
187                         }
188                         
189                         error << string_compose (_("poll on butler request pipe failed (%1)"),
190                                           strerror (errno))
191                               << endmsg;
192                         break;
193                 }
194                 
195                 if (pfd[0].revents & ~POLLIN) {
196                         error << _("Error on butler thread request pipe") << endmsg;
197                         break;
198                 }
199                 
200                 if (pfd[0].revents & POLLIN) {
201                         
202                         char req;
203                         
204                         /* empty the pipe of all current requests */
205                         
206                         while (1) {
207                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
208                                 
209                                 if (nread == 1) {
210                                         
211                                         switch ((ButlerRequest::Type) req) {
212                                                 
213                                         case ButlerRequest::Wake:
214                                                 break;
215                                         case ButlerRequest::Run:
216                                                 butler_should_run = true;
217                                                 break;
218                                                 
219                                         case ButlerRequest::Pause:
220                                                 butler_should_run = false;
221                                                 break;
222                                                 
223                                         case ButlerRequest::Quit:
224                                                 pthread_exit_pbd (0);
225                                                 /*NOTREACHED*/
226                                                 break;
227                                                 
228                                         default:
229                                                 break;
230                                         }
231                                         
232                                 } else if (nread == 0) {
233                                         break;
234                                 } else if (errno == EAGAIN) {
235                                         break;
236                                 } else {
237                                         fatal << _("Error reading from butler request pipe") << endmsg;
238                                         /*NOTREACHED*/
239                                 }
240                         }
241                 }
242         
243 //              for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
244 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
245 //              }
246
247                 if (transport_work_requested()) {
248                         butler_transport_work ();
249                 }
250
251                 disk_work_outstanding = false;
252                 bytes = 0;
253                 compute_io = true;
254
255                 gettimeofday (&begin, 0);
256
257                 RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
258                 
259                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
260                         
261                         // cerr << "rah fondr " << (*i)->io()->name () << endl;
262
263                         switch ((*i)->do_refill (butler_mixdown_buffer, butler_gain_buffer)) {
264                         case 0:
265                                 bytes += (*i)->read_data_count();
266                                 break;
267                         case 1:
268                                 bytes += (*i)->read_data_count();
269                                 disk_work_outstanding = true;
270                                 break;
271                                 
272                         default:
273                                 compute_io = false;
274                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
275                                 break;
276                         }
277
278                 }
279
280                 if (i != diskstreams.end()) {
281                         /* we didn't get to all the streams */
282                         disk_work_outstanding = true;
283                 }
284                 
285                 if (!err && transport_work_requested()) {
286                         continue;
287                 }
288
289                 if (compute_io) {
290                         gettimeofday (&end, 0);
291                         
292                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
293                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
294                         
295                         _read_data_rate = bytes / (e - b);
296                 }
297
298                 bytes = 0;
299                 compute_io = true;
300                 gettimeofday (&begin, 0);
301                 
302                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
303                         
304                         // cerr << "write behind for " << (*i)->name () << endl;
305                         
306                         switch ((*i)->do_flush ()) {
307                         case 0:
308                                 bytes += (*i)->write_data_count();
309                                 break;
310                         case 1:
311                                 bytes += (*i)->write_data_count();
312                                 disk_work_outstanding = true;
313                                 break;
314                                 
315                         default:
316                                 err++;
317                                 compute_io = false;
318                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
319                                 /* don't break - try to flush all streams in case they 
320                                    are split across disks.
321                                 */
322                         }
323                 }
324
325                 if (err && actively_recording()) {
326                         /* stop the transport and try to catch as much possible
327                            captured state as we can.
328                         */
329                         request_stop ();
330                 }
331
332                 if (i != diskstreams.end()) {
333                         /* we didn't get to all the streams */
334                         disk_work_outstanding = true;
335                 }
336                 
337                 if (!err && transport_work_requested()) {
338                         continue;
339                 }
340
341                 if (compute_io) {
342                         gettimeofday (&end, 0);
343                         
344                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
345                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
346                         
347                         _write_data_rate = bytes / (e - b);
348                 }
349                 
350                 if (!disk_work_outstanding) {
351                         refresh_disk_space ();
352                 }
353
354
355                 {
356                         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
357
358                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
359 //                              for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
360 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
361 //                              }
362
363                                 continue;
364                         }
365
366                         pthread_cond_signal (&butler_paused);
367                 }
368         }
369
370         pthread_exit_pbd (0);
371         /*NOTREACHED*/
372         return (0);
373 }
374
375
376 void
377 Session::request_overwrite_buffer (DiskStream* stream)
378 {
379         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
380         ev->set_ptr (stream);
381         queue_event (ev);
382 }
383
384 void
385 Session::overwrite_some_buffers (DiskStream* ds)
386 {
387         /* executed by the audio thread */
388
389         if (actively_recording()) {
390                 return;
391         }
392
393         if (ds) {
394
395                 ds->set_pending_overwrite (true);
396
397         } else {
398
399                 RWLockMonitor dm (diskstream_lock, false, __LINE__, __FILE__);
400                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
401                         (*i)->set_pending_overwrite (true);
402                 }
403         }
404
405         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
406         schedule_butler_transport_work ();
407 }
408
409 float
410 Session::read_data_rate () const
411 {
412         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
413            in action. ignore it.
414         */
415         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
416 }
417
418 float
419 Session::write_data_rate () const
420 {
421         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
422            in action. ignore it.
423         */
424         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
425 }
426
427 uint32_t
428 Session::playback_load ()
429 {
430         return (uint32_t) atomic_read (&_playback_load);
431 }
432
433 uint32_t
434 Session::capture_load ()
435 {
436         return (uint32_t) atomic_read (&_capture_load);
437 }
438
439 uint32_t
440 Session::playback_load_min ()
441 {
442         return (uint32_t) atomic_read (&_playback_load_min);
443 }
444
445 uint32_t
446 Session::capture_load_min ()
447 {
448         return (uint32_t) atomic_read (&_capture_load_min);
449 }
450
451 void
452 Session::reset_capture_load_min ()
453 {
454         atomic_set (&_capture_load_min, 100);
455 }
456
457
458 void
459 Session::reset_playback_load_min ()
460 {
461         atomic_set (&_playback_load_min, 100);
462 }