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