merge with 2.0-ongoing @ rev 3147
[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 #include <pbd/stacktrace.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         if (butler_thread) {
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
115 void
116 Session::schedule_butler_transport_work ()
117 {
118         g_atomic_int_inc (&butler_should_do_transport_work);
119         summon_butler ();
120 }
121
122 void
123 Session::schedule_curve_reallocation ()
124 {
125         post_transport_work = PostTransportWork (post_transport_work | PostTransportCurveRealloc);
126         schedule_butler_transport_work ();
127 }
128
129 void
130 Session::summon_butler ()
131 {
132         char c = ButlerRequest::Run;
133         ::write (butler_request_pipe[1], &c, 1);
134         // PBD::stacktrace (cerr);
135 }
136
137 void
138 Session::stop_butler ()
139 {
140         Glib::Mutex::Lock lm (butler_request_lock);
141         char c = ButlerRequest::Pause;
142         ::write (butler_request_pipe[1], &c, 1);
143         butler_paused.wait(butler_request_lock);
144 }
145
146 void
147 Session::wait_till_butler_finished ()
148 {
149         Glib::Mutex::Lock lm (butler_request_lock);
150         char c = ButlerRequest::Wake;
151         ::write (butler_request_pipe[1], &c, 1);
152         butler_paused.wait(butler_request_lock);
153 }
154
155 void *
156 Session::_butler_thread_work (void* arg)
157 {
158         PBD::ThreadCreated (pthread_self(), X_("Butler"));
159         return ((Session *) arg)->butler_thread_work ();
160         return 0;
161 }
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         while (true) {
175                 pfd[0].fd = butler_request_pipe[0];
176                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
177                 
178                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
179                         
180                         if (errno == EINTR) {
181                                 continue;
182                         }
183                         
184                         error << string_compose (_("poll on butler request pipe failed (%1)"),
185                                           strerror (errno))
186                               << endmsg;
187                         break;
188                 }
189
190                 if (pfd[0].revents & ~POLLIN) {
191                         error << string_compose (_("Error on butler thread request pipe: fd=%1 err=%2"), pfd[0].fd, pfd[0].revents) << endmsg;
192                         break;
193                 }
194                 
195                 if (pfd[0].revents & POLLIN) {
196
197                         char req;
198                         
199                         /* empty the pipe of all current requests */
200                         
201                         while (1) {
202                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
203                                 if (nread == 1) {
204                                         
205                                         switch ((ButlerRequest::Type) req) {
206                                                 
207                                         case ButlerRequest::Wake:
208                                                 break;
209
210                                         case ButlerRequest::Run:
211                                                 butler_should_run = true;
212                                                 break;
213                                                 
214                                         case ButlerRequest::Pause:
215                                                 butler_should_run = false;
216                                                 break;
217                                                 
218                                         case ButlerRequest::Quit:
219                                                 pthread_exit_pbd (0);
220                                                 /*NOTREACHED*/
221                                                 break;
222                                                 
223                                         default:
224                                                 break;
225                                         }
226                                         
227                                 } else if (nread == 0) {
228                                         break;
229                                 } else if (errno == EAGAIN) {
230                                         break;
231                                 } else {
232                                         fatal << _("Error reading from butler request pipe") << endmsg;
233                                         /*NOTREACHED*/
234                                 }
235                         }
236                 }
237
238                 if (transport_work_requested()) {
239                         butler_transport_work ();
240                 }
241
242                 disk_work_outstanding = false;
243                 bytes = 0;
244                 compute_io = true;
245
246                 gettimeofday (&begin, 0);
247
248                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
249
250 //              for (i = dsl->begin(); i != dsl->end(); ++i) {
251 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
252 //              }
253
254                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
255
256                         boost::shared_ptr<Diskstream> ds = *i;
257
258                         /* don't read inactive tracks */
259
260                         /*IO* io = ds->io();
261                         
262                         if (io && !io->active()) {
263                                 continue;
264                         }*/
265
266                         switch (ds->do_refill ()) {
267                         case 0:
268                                 bytes += ds->read_data_count();
269                                 break;
270                         case 1:
271                                 bytes += ds->read_data_count();
272                                 disk_work_outstanding = true;
273                                 break;
274                                 
275                         default:
276                                 compute_io = false;
277                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
278                                 break;
279                         }
280
281                 }
282
283                 if (i != dsl->end()) {
284                         /* we didn't get to all the streams */
285                         disk_work_outstanding = true;
286                 }
287                 
288                 if (!err && transport_work_requested()) {
289                         continue;
290                 }
291
292                 if (compute_io) {
293                         gettimeofday (&end, 0);
294                         
295                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
296                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
297                         
298                         _read_data_rate = bytes / (e - b);
299                 }
300
301                 bytes = 0;
302                 compute_io = true;
303                 gettimeofday (&begin, 0);
304
305                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
306                         // cerr << "write behind for " << (*i)->name () << endl;
307
308                         /* note that we still try to flush diskstreams attached to inactive routes
309                          */
310                         
311                         switch ((*i)->do_flush (Session::ButlerContext)) {
312                         case 0:
313                                 bytes += (*i)->write_data_count();
314                                 break;
315                         case 1:
316                                 bytes += (*i)->write_data_count();
317                                 disk_work_outstanding = true;
318                                 break;
319                                 
320                         default:
321                                 err++;
322                                 compute_io = false;
323                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
324                                 /* don't break - try to flush all streams in case they 
325                                    are split across disks.
326                                 */
327                         }
328                 }
329
330                 if (err && actively_recording()) {
331                         /* stop the transport and try to catch as much possible
332                            captured state as we can.
333                         */
334                         request_stop ();
335                 }
336
337                 if (i != dsl->end()) {
338                         /* we didn't get to all the streams */
339                         disk_work_outstanding = true;
340                 }
341                 
342                 if (!err && transport_work_requested()) {
343                         continue;
344                 }
345
346                 if (compute_io) {
347                         gettimeofday (&end, 0);
348                         
349                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
350                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
351                         
352                         _write_data_rate = bytes / (e - b);
353                 }
354                 
355                 if (!disk_work_outstanding) {
356                         refresh_disk_space ();
357                 }
358
359
360                 {
361                         Glib::Mutex::Lock lm (butler_request_lock);
362
363                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
364 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
365 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
366 //                              }
367
368                                 continue;
369                         }
370
371                         butler_paused.signal();
372                 }
373         }
374
375         pthread_exit_pbd (0);
376         /*NOTREACHED*/
377         return (0);
378 }
379
380
381 void
382 Session::request_overwrite_buffer (Diskstream* stream)
383 {
384         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
385         ev->set_ptr (stream);
386         queue_event (ev);
387 }
388
389 /** Process thread. */
390 void
391 Session::overwrite_some_buffers (Diskstream* ds)
392 {
393         if (actively_recording()) {
394                 return;
395         }
396
397         if (ds) {
398
399                 ds->set_pending_overwrite (true);
400
401         } else {
402
403                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
404                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
405                         (*i)->set_pending_overwrite (true);
406                 }
407         }
408
409         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
410         schedule_butler_transport_work ();
411 }
412
413 float
414 Session::read_data_rate () const
415 {
416         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
417            in action. ignore it.
418         */
419         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
420 }
421
422 float
423 Session::write_data_rate () const
424 {
425         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
426            in action. ignore it.
427         */
428         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
429 }
430
431 uint32_t
432 Session::playback_load ()
433 {
434         return (uint32_t) g_atomic_int_get (&_playback_load);
435 }
436
437 uint32_t
438 Session::capture_load ()
439 {
440         return (uint32_t) g_atomic_int_get (&_capture_load);
441 }
442
443 uint32_t
444 Session::playback_load_min ()
445 {
446         return (uint32_t) g_atomic_int_get (&_playback_load_min);
447 }
448
449 uint32_t
450 Session::capture_load_min ()
451 {
452         return (uint32_t) g_atomic_int_get (&_capture_load_min);
453 }
454
455 void
456 Session::reset_capture_load_min ()
457 {
458         g_atomic_int_set (&_capture_load_min, 100);
459 }
460
461
462 void
463 Session::reset_playback_load_min ()
464 {
465         g_atomic_int_set (&_playback_load_min, 100);
466 }