Merging from trunk
[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         AudioDiskstreamList::iterator i;
172
173         butler_mixdown_buffer = new Sample[AudioDiskstream::disk_io_frames()];
174         butler_gain_buffer = new gain_t[AudioDiskstream::disk_io_frames()];
175         // this buffer is used for temp conversion purposes in filesources
176         char * conv_buffer = conversion_buffer(ButlerContext);
177
178         while (true) {
179
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 << _("Error on butler thread request pipe") << 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                                 
209                                 if (nread == 1) {
210                                         
211                                         switch ((ButlerRequest::Type) req) {
212                                                 
213                                         case ButlerRequest::Wake:
214                                                 break;
215
216                                         case ButlerRequest::Run:
217                                                 butler_should_run = true;
218                                                 break;
219                                                 
220                                         case ButlerRequest::Pause:
221                                                 butler_should_run = false;
222                                                 break;
223                                                 
224                                         case ButlerRequest::Quit:
225                                                 pthread_exit_pbd (0);
226                                                 /*NOTREACHED*/
227                                                 break;
228                                                 
229                                         default:
230                                                 break;
231                                         }
232                                         
233                                 } else if (nread == 0) {
234                                         break;
235                                 } else if (errno == EAGAIN) {
236                                         break;
237                                 } else {
238                                         fatal << _("Error reading from butler request pipe") << endmsg;
239                                         /*NOTREACHED*/
240                                 }
241                         }
242                 }
243         
244                 for (i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
245                         // cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
246                 }
247
248                 if (transport_work_requested()) {
249                         butler_transport_work ();
250                 }
251
252                 disk_work_outstanding = false;
253                 bytes = 0;
254                 compute_io = true;
255
256                 gettimeofday (&begin, 0);
257
258                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
259                 
260                 for (i = audio_diskstreams.begin(); !transport_work_requested() && butler_should_run && i != audio_diskstreams.end(); ++i) {
261                         
262                         // cerr << "rah fondr " << (*i)->io()->name () << endl;
263
264                         switch ((*i)->do_refill (butler_mixdown_buffer, butler_gain_buffer, conv_buffer)) {
265                         case 0:
266                                 bytes += (*i)->read_data_count();
267                                 break;
268                         case 1:
269                                 bytes += (*i)->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 != audio_diskstreams.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 = audio_diskstreams.begin(); !transport_work_requested() && butler_should_run && i != audio_diskstreams.end(); ++i) {
304                         
305                         // cerr << "write behind for " << (*i)->name () << endl;
306                         
307                         switch ((*i)->do_flush (conv_buffer)) {
308                         case 0:
309                                 bytes += (*i)->write_data_count();
310                                 break;
311                         case 1:
312                                 bytes += (*i)->write_data_count();
313                                 disk_work_outstanding = true;
314                                 break;
315                                 
316                         default:
317                                 err++;
318                                 compute_io = false;
319                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
320                                 /* don't break - try to flush all streams in case they 
321                                    are split across disks.
322                                 */
323                         }
324                 }
325
326                 if (err && actively_recording()) {
327                         /* stop the transport and try to catch as much possible
328                            captured state as we can.
329                         */
330                         request_stop ();
331                 }
332
333                 if (i != audio_diskstreams.end()) {
334                         /* we didn't get to all the streams */
335                         disk_work_outstanding = true;
336                 }
337                 
338                 if (!err && transport_work_requested()) {
339                         continue;
340                 }
341
342                 if (compute_io) {
343                         gettimeofday (&end, 0);
344                         
345                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
346                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
347                         
348                         _write_data_rate = bytes / (e - b);
349                 }
350                 
351                 if (!disk_work_outstanding) {
352                         refresh_disk_space ();
353                 }
354
355
356                 {
357                         Glib::Mutex::Lock lm (butler_request_lock);
358
359                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
360 //                              for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
361 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
362 //                              }
363
364                                 continue;
365                         }
366
367                         butler_paused.signal();
368                 }
369         }
370
371         pthread_exit_pbd (0);
372         /*NOTREACHED*/
373         return (0);
374 }
375
376
377 void
378 Session::request_overwrite_buffer (AudioDiskstream* stream)
379 {
380         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
381         ev->set_ptr (stream);
382         queue_event (ev);
383 }
384
385 void
386 Session::overwrite_some_buffers (AudioDiskstream* ds)
387 {
388         /* executed by the audio thread */
389
390         if (actively_recording()) {
391                 return;
392         }
393
394         if (ds) {
395
396                 ds->set_pending_overwrite (true);
397
398         } else {
399
400                 Glib::RWLock::ReaderLock dm (diskstream_lock);
401                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
402                         (*i)->set_pending_overwrite (true);
403                 }
404         }
405
406         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
407         schedule_butler_transport_work ();
408 }
409
410 float
411 Session::read_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 _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
417 }
418
419 float
420 Session::write_data_rate () const
421 {
422         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
423            in action. ignore it.
424         */
425         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
426 }
427
428 uint32_t
429 Session::playback_load ()
430 {
431         return (uint32_t) g_atomic_int_get (&_playback_load);
432 }
433
434 uint32_t
435 Session::capture_load ()
436 {
437         return (uint32_t) g_atomic_int_get (&_capture_load);
438 }
439
440 uint32_t
441 Session::playback_load_min ()
442 {
443         return (uint32_t) g_atomic_int_get (&_playback_load_min);
444 }
445
446 uint32_t
447 Session::capture_load_min ()
448 {
449         return (uint32_t) g_atomic_int_get (&_capture_load_min);
450 }
451
452 void
453 Session::reset_capture_load_min ()
454 {
455         g_atomic_int_set (&_capture_load_min, 100);
456 }
457
458
459 void
460 Session::reset_playback_load_min ()
461 {
462         g_atomic_int_set (&_playback_load_min, 100);
463 }