Large nasty commit in the form of a 5000 line patch chock-full of completely
[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                 pfd[0].fd = butler_request_pipe[0];
180                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
181                 
182                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
183                         
184                         if (errno == EINTR) {
185                                 continue;
186                         }
187                         
188                         error << string_compose (_("poll on butler request pipe failed (%1)"),
189                                           strerror (errno))
190                               << endmsg;
191                         break;
192                 }
193
194                 if (pfd[0].revents & ~POLLIN) {
195                         error << _("Error on butler thread request pipe") << endmsg;
196                         break;
197                 }
198                 
199                 if (pfd[0].revents & POLLIN) {
200
201                         char req;
202                         
203                         /* empty the pipe of all current requests */
204                         
205                         while (1) {
206                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
207                                 if (nread == 1) {
208                                         
209                                         switch ((ButlerRequest::Type) req) {
210                                                 
211                                         case ButlerRequest::Wake:
212                                                 break;
213
214                                         case ButlerRequest::Run:
215                                                 butler_should_run = true;
216                                                 break;
217                                                 
218                                         case ButlerRequest::Pause:
219                                                 butler_should_run = false;
220                                                 break;
221                                                 
222                                         case ButlerRequest::Quit:
223                                                 pthread_exit_pbd (0);
224                                                 /*NOTREACHED*/
225                                                 break;
226                                                 
227                                         default:
228                                                 break;
229                                         }
230                                         
231                                 } else if (nread == 0) {
232                                         break;
233                                 } else if (errno == EAGAIN) {
234                                         break;
235                                 } else {
236                                         fatal << _("Error reading from butler request pipe") << endmsg;
237                                         /*NOTREACHED*/
238                                 }
239                         }
240                 }
241
242                 //for (i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
243                         // cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
244                 //}
245
246                 if (transport_work_requested()) {
247                         butler_transport_work ();
248                 }
249
250                 disk_work_outstanding = false;
251                 bytes = 0;
252                 compute_io = true;
253
254                 gettimeofday (&begin, 0);
255
256                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
257                 
258                 for (i = audio_diskstreams.begin(); !transport_work_requested() && butler_should_run && i != audio_diskstreams.end(); ++i) {
259                         // cerr << "rah fondr " << (*i)->io()->name () << endl;
260
261                         switch ((*i)->do_refill (butler_mixdown_buffer, butler_gain_buffer, conv_buffer)) {
262                         case 0:
263                                 bytes += (*i)->read_data_count();
264                                 break;
265                         case 1:
266                                 bytes += (*i)->read_data_count();
267                                 disk_work_outstanding = true;
268                                 break;
269                                 
270                         default:
271                                 compute_io = false;
272                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
273                                 break;
274                         }
275
276                 }
277
278                 if (i != audio_diskstreams.end()) {
279                         /* we didn't get to all the streams */
280                         disk_work_outstanding = true;
281                 }
282                 
283                 if (!err && transport_work_requested()) {
284                         continue;
285                 }
286
287                 if (compute_io) {
288                         gettimeofday (&end, 0);
289                         
290                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
291                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
292                         
293                         _read_data_rate = bytes / (e - b);
294                 }
295
296                 bytes = 0;
297                 compute_io = true;
298                 gettimeofday (&begin, 0);
299
300                 for (i = audio_diskstreams.begin(); !transport_work_requested() && butler_should_run && i != audio_diskstreams.end(); ++i) {
301                         // cerr << "write behind for " << (*i)->name () << endl;
302                         
303                         switch ((*i)->do_flush (conv_buffer)) {
304                         case 0:
305                                 bytes += (*i)->write_data_count();
306                                 break;
307                         case 1:
308                                 bytes += (*i)->write_data_count();
309                                 disk_work_outstanding = true;
310                                 break;
311                                 
312                         default:
313                                 err++;
314                                 compute_io = false;
315                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
316                                 /* don't break - try to flush all streams in case they 
317                                    are split across disks.
318                                 */
319                         }
320                 }
321
322                 if (err && actively_recording()) {
323                         /* stop the transport and try to catch as much possible
324                            captured state as we can.
325                         */
326                         request_stop ();
327                 }
328
329                 if (i != audio_diskstreams.end()) {
330                         /* we didn't get to all the streams */
331                         disk_work_outstanding = true;
332                 }
333                 
334                 if (!err && transport_work_requested()) {
335                         continue;
336                 }
337
338                 if (compute_io) {
339                         gettimeofday (&end, 0);
340                         
341                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
342                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
343                         
344                         _write_data_rate = bytes / (e - b);
345                 }
346                 
347                 if (!disk_work_outstanding) {
348                         refresh_disk_space ();
349                 }
350
351
352                 {
353                         Glib::Mutex::Lock lm (butler_request_lock);
354
355                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
356 //                              for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
357 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
358 //                              }
359
360                                 continue;
361                         }
362
363                         butler_paused.signal();
364                 }
365         }
366
367         pthread_exit_pbd (0);
368         /*NOTREACHED*/
369         return (0);
370 }
371
372
373 void
374 Session::request_overwrite_buffer (Diskstream* stream)
375 {
376         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
377         ev->set_ptr (stream);
378         queue_event (ev);
379 }
380
381 /** Process thread. */
382 void
383 Session::overwrite_some_buffers (Diskstream* ds)
384 {
385         if (actively_recording()) {
386                 return;
387         }
388
389         if (ds) {
390
391                 ds->set_pending_overwrite (true);
392
393         } else {
394
395                 Glib::RWLock::ReaderLock dm (diskstream_lock);
396                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
397                         (*i)->set_pending_overwrite (true);
398                 }
399         }
400
401         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
402         schedule_butler_transport_work ();
403 }
404
405 float
406 Session::read_data_rate () const
407 {
408         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
409            in action. ignore it.
410         */
411         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
412 }
413
414 float
415 Session::write_data_rate () const
416 {
417         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
418            in action. ignore it.
419         */
420         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
421 }
422
423 uint32_t
424 Session::playback_load ()
425 {
426         return (uint32_t) g_atomic_int_get (&_playback_load);
427 }
428
429 uint32_t
430 Session::capture_load ()
431 {
432         return (uint32_t) g_atomic_int_get (&_capture_load);
433 }
434
435 uint32_t
436 Session::playback_load_min ()
437 {
438         return (uint32_t) g_atomic_int_get (&_playback_load_min);
439 }
440
441 uint32_t
442 Session::capture_load_min ()
443 {
444         return (uint32_t) g_atomic_int_get (&_capture_load_min);
445 }
446
447 void
448 Session::reset_capture_load_min ()
449 {
450         g_atomic_int_set (&_capture_load_min, 100);
451 }
452
453
454 void
455 Session::reset_playback_load_min ()
456 {
457         g_atomic_int_set (&_playback_load_min, 100);
458 }