rollback to 3428, before the mysterious removal of libs/* at 3431/3432
[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         audio_dstream_buffer_size = (uint32_t) floor (Config->get_audio_track_buffer_seconds() * (float) frame_rate());
73         
74         /* size is in bytes
75          * XXX: Jack needs to tell us the MIDI buffer size
76          * (i.e. how many MIDI bytes we might see in a cycle)
77          */
78         midi_dstream_buffer_size = (uint32_t) floor (Config->get_midi_track_buffer_seconds() * (float)frame_rate());
79         
80         Crossfade::set_buffer_size (audio_dstream_buffer_size);
81
82         butler_should_run = false;
83
84         if (pipe (butler_request_pipe)) {
85                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
86                 return -1;
87         }
88
89         if (fcntl (butler_request_pipe[0], 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 (fcntl (butler_request_pipe[1], F_SETFL, O_NONBLOCK)) {
95                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
96                 return -1;
97         }
98
99         if (pthread_create_and_store ("disk butler", &butler_thread, 0, _butler_thread_work, this)) {
100                 error << _("Session: could not create butler thread") << endmsg;
101                 return -1;
102         }
103
104         // pthread_detach (butler_thread);
105
106         return 0;
107 }
108
109 void
110 Session::terminate_butler_thread ()
111 {
112         if (butler_thread) {
113                 void* status;
114                 char c = ButlerRequest::Quit;
115                 ::write (butler_request_pipe[1], &c, 1);
116                 pthread_join (butler_thread, &status);
117         }
118 }
119
120 void
121 Session::schedule_butler_transport_work ()
122 {
123         g_atomic_int_inc (&butler_should_do_transport_work);
124         summon_butler ();
125 }
126
127 void
128 Session::schedule_curve_reallocation ()
129 {
130         post_transport_work = PostTransportWork (post_transport_work | PostTransportCurveRealloc);
131         schedule_butler_transport_work ();
132 }
133
134 void
135 Session::summon_butler ()
136 {
137         char c = ButlerRequest::Run;
138         ::write (butler_request_pipe[1], &c, 1);
139         // PBD::stacktrace (cerr);
140 }
141
142 void
143 Session::stop_butler ()
144 {
145         Glib::Mutex::Lock lm (butler_request_lock);
146         char c = ButlerRequest::Pause;
147         ::write (butler_request_pipe[1], &c, 1);
148         butler_paused.wait(butler_request_lock);
149 }
150
151 void
152 Session::wait_till_butler_finished ()
153 {
154         Glib::Mutex::Lock lm (butler_request_lock);
155         char c = ButlerRequest::Wake;
156         ::write (butler_request_pipe[1], &c, 1);
157         butler_paused.wait(butler_request_lock);
158 }
159
160 void *
161 Session::_butler_thread_work (void* arg)
162 {
163         PBD::ThreadCreated (pthread_self(), X_("Butler"));
164         return ((Session *) arg)->butler_thread_work ();
165         return 0;
166 }
167
168 void *
169 Session::butler_thread_work ()
170 {
171         uint32_t err = 0;
172         int32_t bytes;
173         bool compute_io;
174         struct timeval begin, end;
175         struct pollfd pfd[1];
176         bool disk_work_outstanding = false;
177         DiskstreamList::iterator i;
178
179         while (true) {
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 << string_compose (_("Error on butler thread request pipe: fd=%1 err=%2"), pfd[0].fd, pfd[0].revents) << 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                                 if (nread == 1) {
209                                         
210                                         switch ((ButlerRequest::Type) req) {
211                                                 
212                                         case ButlerRequest::Wake:
213                                                 break;
214
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                 if (transport_work_requested()) {
244                         butler_transport_work ();
245                 }
246
247                 disk_work_outstanding = false;
248                 bytes = 0;
249                 compute_io = true;
250
251                 gettimeofday (&begin, 0);
252
253                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
254
255 //              for (i = dsl->begin(); i != dsl->end(); ++i) {
256 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
257 //              }
258
259                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
260
261                         boost::shared_ptr<Diskstream> ds = *i;
262
263                         /* don't read inactive tracks */
264
265                         IO* io = ds->io();
266                         
267                         if (io && !io->active()) {
268                                 continue;
269                         }
270
271                         switch (ds->do_refill ()) {
272                         case 0:
273                                 bytes += ds->read_data_count();
274                                 break;
275                         case 1:
276                                 bytes += ds->read_data_count();
277                                 disk_work_outstanding = true;
278                                 break;
279                                 
280                         default:
281                                 compute_io = false;
282                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
283                                 break;
284                         }
285
286                 }
287
288                 if (i != dsl->end()) {
289                         /* we didn't get to all the streams */
290                         disk_work_outstanding = true;
291                 }
292                 
293                 if (!err && transport_work_requested()) {
294                         continue;
295                 }
296
297                 if (compute_io) {
298                         gettimeofday (&end, 0);
299                         
300                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
301                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
302                         
303                         _read_data_rate = bytes / (e - b);
304                 }
305
306                 bytes = 0;
307                 compute_io = true;
308                 gettimeofday (&begin, 0);
309
310                 for (i = dsl->begin(); !transport_work_requested() && butler_should_run && i != dsl->end(); ++i) {
311                         // cerr << "write behind for " << (*i)->name () << endl;
312
313                         /* note that we still try to flush diskstreams attached to inactive routes
314                          */
315                         
316                         switch ((*i)->do_flush (Session::ButlerContext)) {
317                         case 0:
318                                 bytes += (*i)->write_data_count();
319                                 break;
320                         case 1:
321                                 bytes += (*i)->write_data_count();
322                                 disk_work_outstanding = true;
323                                 break;
324                                 
325                         default:
326                                 err++;
327                                 compute_io = false;
328                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
329                                 /* don't break - try to flush all streams in case they 
330                                    are split across disks.
331                                 */
332                         }
333                 }
334
335                 if (err && actively_recording()) {
336                         /* stop the transport and try to catch as much possible
337                            captured state as we can.
338                         */
339                         request_stop ();
340                 }
341
342                 if (i != dsl->end()) {
343                         /* we didn't get to all the streams */
344                         disk_work_outstanding = true;
345                 }
346                 
347                 if (!err && transport_work_requested()) {
348                         continue;
349                 }
350
351                 if (compute_io) {
352                         gettimeofday (&end, 0);
353                         
354                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
355                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
356                         
357                         _write_data_rate = bytes / (e - b);
358                 }
359                 
360                 if (!disk_work_outstanding) {
361                         refresh_disk_space ();
362                 }
363
364
365                 {
366                         Glib::Mutex::Lock lm (butler_request_lock);
367
368                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
369 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
370 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
371 //                              }
372
373                                 continue;
374                         }
375
376                         butler_paused.signal();
377                 }
378         }
379
380         pthread_exit_pbd (0);
381         /*NOTREACHED*/
382         return (0);
383 }
384
385
386 void
387 Session::request_overwrite_buffer (Diskstream* stream)
388 {
389         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
390         ev->set_ptr (stream);
391         queue_event (ev);
392 }
393
394 /** Process thread. */
395 void
396 Session::overwrite_some_buffers (Diskstream* ds)
397 {
398         if (actively_recording()) {
399                 return;
400         }
401
402         if (ds) {
403
404                 ds->set_pending_overwrite (true);
405
406         } else {
407
408                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
409                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
410                         (*i)->set_pending_overwrite (true);
411                 }
412         }
413
414         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
415         schedule_butler_transport_work ();
416 }
417
418 float
419 Session::read_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 _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
425 }
426
427 float
428 Session::write_data_rate () const
429 {
430         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
431            in action. ignore it.
432         */
433         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
434 }
435
436 uint32_t
437 Session::playback_load ()
438 {
439         return (uint32_t) g_atomic_int_get (&_playback_load);
440 }
441
442 uint32_t
443 Session::capture_load ()
444 {
445         return (uint32_t) g_atomic_int_get (&_capture_load);
446 }
447
448 uint32_t
449 Session::playback_load_min ()
450 {
451         return (uint32_t) g_atomic_int_get (&_playback_load_min);
452 }
453
454 uint32_t
455 Session::capture_load_min ()
456 {
457         return (uint32_t) g_atomic_int_get (&_capture_load_min);
458 }
459
460 void
461 Session::reset_capture_load_min ()
462 {
463         g_atomic_int_set (&_capture_load_min, 100);
464 }
465
466
467 void
468 Session::reset_playback_load_min ()
469 {
470         g_atomic_int_set (&_playback_load_min, 100);
471 }