Merge with 2.0-ongoing R2883.
[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                 if (transport_work_requested()) {
237                         butler_transport_work ();
238                 }
239
240                 disk_work_outstanding = false;
241                 bytes = 0;
242                 compute_io = true;
243
244                 gettimeofday (&begin, 0);
245
246                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
247
248 //              for (i = dsl->begin(); i != dsl->end(); ++i) {
249 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
250 //              }
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                         /* don't read inactive tracks */
257
258                         /*IO* io = ds->io();
259                         
260                         if (io && !io->active()) {
261                                 continue;
262                         }*/
263
264                         switch (ds->do_refill ()) {
265                         case 0:
266                                 bytes += ds->read_data_count();
267                                 break;
268                         case 1:
269                                 bytes += ds->read_data_count();
270                                 disk_work_outstanding = true;
271                                 break;
272                                 
273                         default:
274                                 compute_io = false;
275                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
276                                 break;
277                         }
278
279                 }
280
281                 if (i != dsl->end()) {
282                         /* we didn't get to all the streams */
283                         disk_work_outstanding = true;
284                 }
285                 
286                 if (!err && transport_work_requested()) {
287                         continue;
288                 }
289
290                 if (compute_io) {
291                         gettimeofday (&end, 0);
292                         
293                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
294                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
295                         
296                         _read_data_rate = bytes / (e - b);
297                 }
298
299                 bytes = 0;
300                 compute_io = true;
301                 gettimeofday (&begin, 0);
302
303                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
304                         // cerr << "write behind for " << (*i)->name () << endl;
305
306                         /* note that we still try to flush diskstreams attached to inactive routes
307                          */
308                         
309                         switch ((*i)->do_flush (Session::ButlerContext)) {
310                         case 0:
311                                 bytes += (*i)->write_data_count();
312                                 break;
313                         case 1:
314                                 bytes += (*i)->write_data_count();
315                                 disk_work_outstanding = true;
316                                 break;
317                                 
318                         default:
319                                 err++;
320                                 compute_io = false;
321                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
322                                 /* don't break - try to flush all streams in case they 
323                                    are split across disks.
324                                 */
325                         }
326                 }
327
328                 if (err && actively_recording()) {
329                         /* stop the transport and try to catch as much possible
330                            captured state as we can.
331                         */
332                         request_stop ();
333                 }
334
335                 if (i != dsl->end()) {
336                         /* we didn't get to all the streams */
337                         disk_work_outstanding = true;
338                 }
339                 
340                 if (!err && transport_work_requested()) {
341                         continue;
342                 }
343
344                 if (compute_io) {
345                         gettimeofday (&end, 0);
346                         
347                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
348                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
349                         
350                         _write_data_rate = bytes / (e - b);
351                 }
352                 
353                 if (!disk_work_outstanding) {
354                         refresh_disk_space ();
355                 }
356
357
358                 {
359                         Glib::Mutex::Lock lm (butler_request_lock);
360
361                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
362 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
363 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
364 //                              }
365
366                                 continue;
367                         }
368
369                         butler_paused.signal();
370                 }
371         }
372
373         pthread_exit_pbd (0);
374         /*NOTREACHED*/
375         return (0);
376 }
377
378
379 void
380 Session::request_overwrite_buffer (Diskstream* stream)
381 {
382         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
383         ev->set_ptr (stream);
384         queue_event (ev);
385 }
386
387 /** Process thread. */
388 void
389 Session::overwrite_some_buffers (Diskstream* ds)
390 {
391         if (actively_recording()) {
392                 return;
393         }
394
395         if (ds) {
396
397                 ds->set_pending_overwrite (true);
398
399         } else {
400
401                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
402                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->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) g_atomic_int_get (&_playback_load);
433 }
434
435 uint32_t
436 Session::capture_load ()
437 {
438         return (uint32_t) g_atomic_int_get (&_capture_load);
439 }
440
441 uint32_t
442 Session::playback_load_min ()
443 {
444         return (uint32_t) g_atomic_int_get (&_playback_load_min);
445 }
446
447 uint32_t
448 Session::capture_load_min ()
449 {
450         return (uint32_t) g_atomic_int_get (&_capture_load_min);
451 }
452
453 void
454 Session::reset_capture_load_min ()
455 {
456         g_atomic_int_set (&_capture_load_min, 100);
457 }
458
459
460 void
461 Session::reset_playback_load_min ()
462 {
463         g_atomic_int_set (&_playback_load_min, 100);
464 }