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