Merged with trunk R1705.
[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 */
19
20 #include <algorithm>
21 #include <string>
22 #include <cmath>
23 #include <cerrno>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <poll.h>
27
28 #include <glibmm/thread.h>
29
30 #include <pbd/error.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/audio_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 PBD;
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         butler_should_run = false;
77
78         if (pipe (butler_request_pipe)) {
79                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
80                 return -1;
81         }
82
83         if (fcntl (butler_request_pipe[0], F_SETFL, O_NONBLOCK)) {
84                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
85                 return -1;
86         }
87
88         if (fcntl (butler_request_pipe[1], F_SETFL, O_NONBLOCK)) {
89                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
90                 return -1;
91         }
92
93         if (pthread_create_and_store ("disk butler", &butler_thread, 0, _butler_thread_work, this)) {
94                 error << _("Session: could not create butler thread") << endmsg;
95                 return -1;
96         }
97
98         // pthread_detach (butler_thread);
99
100         return 0;
101 }
102
103 void
104 Session::terminate_butler_thread ()
105 {
106         if (butler_thread) {
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
114 void
115 Session::schedule_butler_transport_work ()
116 {
117         g_atomic_int_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         Glib::Mutex::Lock lm (butler_request_lock);
139         char c = ButlerRequest::Pause;
140         ::write (butler_request_pipe[1], &c, 1);
141         butler_paused.wait(butler_request_lock);
142 }
143
144 void
145 Session::wait_till_butler_finished ()
146 {
147         Glib::Mutex::Lock lm (butler_request_lock);
148         char c = ButlerRequest::Wake;
149         ::write (butler_request_pipe[1], &c, 1);
150         butler_paused.wait(butler_request_lock);
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 void *
162 Session::butler_thread_work ()
163 {
164         uint32_t err = 0;
165         int32_t bytes;
166         bool compute_io;
167         struct timeval begin, end;
168         struct pollfd pfd[1];
169         bool disk_work_outstanding = false;
170         DiskstreamList::iterator i;
171
172         while (true) {
173                 pfd[0].fd = butler_request_pipe[0];
174                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
175                 
176                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
177                         
178                         if (errno == EINTR) {
179                                 continue;
180                         }
181                         
182                         error << string_compose (_("poll on butler request pipe failed (%1)"),
183                                           strerror (errno))
184                               << endmsg;
185                         break;
186                 }
187
188                 if (pfd[0].revents & ~POLLIN) {
189                         error << string_compose (_("Error on butler thread request pipe: fd=%1 err=%2"), pfd[0].fd, pfd[0].revents) << endmsg;
190                         break;
191                 }
192                 
193                 if (pfd[0].revents & POLLIN) {
194
195                         char req;
196                         
197                         /* empty the pipe of all current requests */
198                         
199                         while (1) {
200                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
201                                 if (nread == 1) {
202                                         
203                                         switch ((ButlerRequest::Type) req) {
204                                                 
205                                         case ButlerRequest::Wake:
206                                                 break;
207
208                                         case ButlerRequest::Run:
209                                                 butler_should_run = true;
210                                                 break;
211                                                 
212                                         case ButlerRequest::Pause:
213                                                 butler_should_run = false;
214                                                 break;
215                                                 
216                                         case ButlerRequest::Quit:
217                                                 pthread_exit_pbd (0);
218                                                 /*NOTREACHED*/
219                                                 break;
220                                                 
221                                         default:
222                                                 break;
223                                         }
224                                         
225                                 } else if (nread == 0) {
226                                         break;
227                                 } else if (errno == EAGAIN) {
228                                         break;
229                                 } else {
230                                         fatal << _("Error reading from butler request pipe") << endmsg;
231                                         /*NOTREACHED*/
232                                 }
233                         }
234                 }
235
236                 //for (i = diskstreams.begin(); i != diskstreams.end(); ++i) {
237                         // cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
238                 //}
239
240                 if (transport_work_requested()) {
241                         butler_transport_work ();
242                 }
243
244                 disk_work_outstanding = false;
245                 bytes = 0;
246                 compute_io = true;
247
248                 gettimeofday (&begin, 0);
249
250                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
251
252                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
253
254                         boost::shared_ptr<Diskstream> ds = *i;
255
256                         switch (ds->do_refill ()) {
257                         case 0:
258                                 bytes += ds->read_data_count();
259                                 break;
260                         case 1:
261                                 bytes += ds->read_data_count();
262                                 disk_work_outstanding = true;
263                                 break;
264                                 
265                         default:
266                                 compute_io = false;
267                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
268                                 break;
269                         }
270
271                 }
272
273                 if (i != dsl->end()) {
274                         /* we didn't get to all the streams */
275                         disk_work_outstanding = true;
276                 }
277                 
278                 if (!err && transport_work_requested()) {
279                         continue;
280                 }
281
282                 if (compute_io) {
283                         gettimeofday (&end, 0);
284                         
285                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
286                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
287                         
288                         _read_data_rate = bytes / (e - b);
289                 }
290
291                 bytes = 0;
292                 compute_io = true;
293                 gettimeofday (&begin, 0);
294
295                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
296                         // cerr << "write behind for " << (*i)->name () << endl;
297                         
298                         switch ((*i)->do_flush (Session::ButlerContext)) {
299                         case 0:
300                                 bytes += (*i)->write_data_count();
301                                 break;
302                         case 1:
303                                 bytes += (*i)->write_data_count();
304                                 disk_work_outstanding = true;
305                                 break;
306                                 
307                         default:
308                                 err++;
309                                 compute_io = false;
310                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
311                                 /* don't break - try to flush all streams in case they 
312                                    are split across disks.
313                                 */
314                         }
315                 }
316
317                 if (err && actively_recording()) {
318                         /* stop the transport and try to catch as much possible
319                            captured state as we can.
320                         */
321                         request_stop ();
322                 }
323
324                 if (i != dsl->end()) {
325                         /* we didn't get to all the streams */
326                         disk_work_outstanding = true;
327                 }
328                 
329                 if (!err && transport_work_requested()) {
330                         continue;
331                 }
332
333                 if (compute_io) {
334                         gettimeofday (&end, 0);
335                         
336                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
337                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
338                         
339                         _write_data_rate = bytes / (e - b);
340                 }
341                 
342                 if (!disk_work_outstanding) {
343                         refresh_disk_space ();
344                 }
345
346
347                 {
348                         Glib::Mutex::Lock lm (butler_request_lock);
349
350                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
351 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
352 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
353 //                              }
354
355                                 continue;
356                         }
357
358                         butler_paused.signal();
359                 }
360         }
361
362         pthread_exit_pbd (0);
363         /*NOTREACHED*/
364         return (0);
365 }
366
367
368 void
369 Session::request_overwrite_buffer (Diskstream* stream)
370 {
371         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
372         ev->set_ptr (stream);
373         queue_event (ev);
374 }
375
376 /** Process thread. */
377 void
378 Session::overwrite_some_buffers (Diskstream* ds)
379 {
380         if (actively_recording()) {
381                 return;
382         }
383
384         if (ds) {
385
386                 ds->set_pending_overwrite (true);
387
388         } else {
389
390                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
391                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
392                         (*i)->set_pending_overwrite (true);
393                 }
394         }
395
396         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
397         schedule_butler_transport_work ();
398 }
399
400 float
401 Session::read_data_rate () const
402 {
403         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
404            in action. ignore it.
405         */
406         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
407 }
408
409 float
410 Session::write_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 _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
416 }
417
418 uint32_t
419 Session::playback_load ()
420 {
421         return (uint32_t) g_atomic_int_get (&_playback_load);
422 }
423
424 uint32_t
425 Session::capture_load ()
426 {
427         return (uint32_t) g_atomic_int_get (&_capture_load);
428 }
429
430 uint32_t
431 Session::playback_load_min ()
432 {
433         return (uint32_t) g_atomic_int_get (&_playback_load_min);
434 }
435
436 uint32_t
437 Session::capture_load_min ()
438 {
439         return (uint32_t) g_atomic_int_get (&_capture_load_min);
440 }
441
442 void
443 Session::reset_capture_load_min ()
444 {
445         g_atomic_int_set (&_capture_load_min, 100);
446 }
447
448
449 void
450 Session::reset_playback_load_min ()
451 {
452         g_atomic_int_set (&_playback_load_min, 100);
453 }