25d8d6c1481e1190292d82184c5871425b5af854
[ardour.git] / libs / ardour / butler.cc
1 /*
2     Copyright (C) 1999-2009 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 <errno.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <poll.h>
24 #include "pbd/error.h"
25 #include "pbd/pthread_utils.h"
26 #include "ardour/butler.h"
27 #include "ardour/crossfade.h"
28 #include "ardour/io.h"
29 #include "ardour/midi_diskstream.h"
30 #include "ardour/session.h"
31
32 #include "i18n.h"
33
34 using namespace PBD;
35
36 static float _read_data_rate;
37 static float _write_data_rate;
38
39 namespace ARDOUR {
40
41 Butler::Butler(Session& s)
42         : SessionHandleRef (s)
43         , thread(0)
44         , audio_dstream_buffer_size(0)
45         , midi_dstream_buffer_size(0)
46 {
47         g_atomic_int_set(&should_do_transport_work, 0);
48 }
49
50 Butler::~Butler()
51 {
52         terminate_thread ();
53 }
54
55 int
56 Butler::start_thread()
57 {
58         const float rate = (float)_session.frame_rate();
59
60         /* size is in Samples, not bytes */
61         audio_dstream_buffer_size = (uint32_t) floor (Config->get_audio_track_buffer_seconds() * rate);
62
63         /* size is in bytes
64          * XXX: Jack needs to tell us the MIDI buffer size
65          * (i.e. how many MIDI bytes we might see in a cycle)
66          */
67         midi_dstream_buffer_size = (uint32_t) floor (Config->get_midi_track_buffer_seconds() * rate);
68
69         MidiDiskstream::set_readahead_frames ((nframes_t)(Config->get_midi_readahead() * rate));
70
71         Crossfade::set_buffer_size (audio_dstream_buffer_size);
72
73         should_run = false;
74
75         if (pipe (request_pipe)) {
76                 error << string_compose(_("Cannot create transport request signal pipe (%1)"),
77                                 strerror (errno)) << endmsg;
78                 return -1;
79         }
80
81         if (fcntl (request_pipe[0], F_SETFL, O_NONBLOCK)) {
82                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"),
83                                 strerror (errno)) << endmsg;
84                 return -1;
85         }
86
87         if (fcntl (request_pipe[1], F_SETFL, O_NONBLOCK)) {
88                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"),
89                                 strerror (errno)) << endmsg;
90                 return -1;
91         }
92
93         if (pthread_create_and_store ("disk butler", &thread, _thread_work, this)) {
94                 error << _("Session: could not create butler thread") << endmsg;
95                 return -1;
96         }
97
98         //pthread_detach (thread);
99
100         return 0;
101 }
102
103 void
104 Butler::terminate_thread ()
105 {
106         if (thread) {
107                 void* status;
108                 const char c = Request::Quit;
109                 ::write (request_pipe[1], &c, 1);
110                 pthread_join (thread, &status);
111         }
112 }
113
114 void *
115 Butler::_thread_work (void* arg)
116 {
117         SessionEvent::create_per_thread_pool ("butler events", 64);
118         return ((Butler *) arg)->thread_work ();
119 }
120
121 void *
122 Butler::thread_work ()
123 {
124         uint32_t err = 0;
125         int32_t bytes;
126         bool compute_io;
127         microseconds_t begin, end;
128
129         struct pollfd pfd[1];
130         bool disk_work_outstanding = false;
131         Session::DiskstreamList::iterator i;
132
133         while (true) {
134                 pfd[0].fd = request_pipe[0];
135                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
136
137                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
138
139                         if (errno == EINTR) {
140                                 continue;
141                         }
142
143                         error << string_compose (_("poll on butler request pipe failed (%1)"),
144                                           strerror (errno))
145                               << endmsg;
146                         break;
147                 }
148
149                 if (pfd[0].revents & ~POLLIN) {
150                         error << string_compose (_("Error on butler thread request pipe: fd=%1 err=%2"), pfd[0].fd, pfd[0].revents) << endmsg;
151                         break;
152                 }
153
154                 if (pfd[0].revents & POLLIN) {
155
156                         char req;
157
158                         /* empty the pipe of all current requests */
159
160                         while (1) {
161                                 size_t nread = ::read (request_pipe[0], &req, sizeof (req));
162                                 if (nread == 1) {
163
164                                         switch ((Request::Type) req) {
165
166                                         case Request::Wake:
167                                                 break;
168
169                                         case Request::Run:
170                                                 should_run = true;
171                                                 break;
172
173                                         case Request::Pause:
174                                                 should_run = false;
175                                                 break;
176
177                                         case Request::Quit:
178                                                 pthread_exit_pbd (0);
179                                                 /*NOTREACHED*/
180                                                 break;
181
182                                         default:
183                                                 break;
184                                         }
185
186                                 } else if (nread == 0) {
187                                         break;
188                                 } else if (errno == EAGAIN) {
189                                         break;
190                                 } else {
191                                         fatal << _("Error reading from butler request pipe") << endmsg;
192                                         /*NOTREACHED*/
193                                 }
194                         }
195                 }
196
197                 if (transport_work_requested()) {
198                         _session.butler_transport_work ();
199                 }
200
201                 disk_work_outstanding = false;
202                 bytes = 0;
203                 compute_io = true;
204
205                 begin = get_microseconds();
206
207                 boost::shared_ptr<Session::DiskstreamList> dsl = _session.diskstream_list().reader ();
208
209 //              for (i = dsl->begin(); i != dsl->end(); ++i) {
210 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
211 //              }
212
213                 for (i = dsl->begin(); !transport_work_requested() && should_run && i != dsl->end(); ++i) {
214
215                         boost::shared_ptr<Diskstream> ds = *i;
216
217                         /* don't read inactive tracks */
218
219                         boost::shared_ptr<IO> io = ds->io();
220
221                         if (io && !io->active()) {
222                                 continue;
223                         }
224
225                         switch (ds->do_refill ()) {
226                         case 0:
227                                 bytes += ds->read_data_count();
228                                 break;
229                         case 1:
230                                 bytes += ds->read_data_count();
231                                 disk_work_outstanding = true;
232                                 break;
233
234                         default:
235                                 compute_io = false;
236                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
237                                 break;
238                         }
239
240                 }
241
242                 if (i != dsl->end()) {
243                         /* we didn't get to all the streams */
244                         disk_work_outstanding = true;
245                 }
246
247                 if (!err && transport_work_requested()) {
248                         continue;
249                 }
250
251                 if (compute_io) {
252                         end = get_microseconds();
253                         if (end - begin > 0) {
254                                 _read_data_rate = (float) bytes / (float) (end - begin);
255                         } else {
256                                 _read_data_rate = 0; // infinity better
257                         }
258                 }
259
260                 bytes = 0;
261                 compute_io = true;
262                 begin = get_microseconds();
263
264                 for (i = dsl->begin(); !transport_work_requested() && should_run && i != dsl->end(); ++i) {
265                         // cerr << "write behind for " << (*i)->name () << endl;
266
267                         /* note that we still try to flush diskstreams attached to inactive routes
268                          */
269
270                         switch ((*i)->do_flush (ButlerContext)) {
271                         case 0:
272                                 bytes += (*i)->write_data_count();
273                                 break;
274                         case 1:
275                                 bytes += (*i)->write_data_count();
276                                 disk_work_outstanding = true;
277                                 break;
278
279                         default:
280                                 err++;
281                                 compute_io = false;
282                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
283                                 /* don't break - try to flush all streams in case they
284                                    are split across disks.
285                                 */
286                         }
287                 }
288
289                 if (err && _session.actively_recording()) {
290                         /* stop the transport and try to catch as much possible
291                            captured state as we can.
292                         */
293                         _session.request_stop ();
294                 }
295
296                 if (i != dsl->end()) {
297                         /* we didn't get to all the streams */
298                         disk_work_outstanding = true;
299                 }
300
301                 if (!err && transport_work_requested()) {
302                         continue;
303                 }
304
305                 if (compute_io) {
306                         // there are no apparent users for this calculation?
307                         end = get_microseconds();
308                         if (end - begin > 0) {
309                                 _write_data_rate = (float) bytes / (float) (end - begin);
310                         } else {
311                                 _write_data_rate = 0; // Well, infinity would be better
312                         }
313                 }
314
315                 if (!disk_work_outstanding) {
316                         _session.refresh_disk_space ();
317                 }
318
319
320                 {
321                         Glib::Mutex::Lock lm (request_lock);
322
323                         if (should_run && (disk_work_outstanding || transport_work_requested())) {
324 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
325 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
326 //                              }
327
328                                 continue;
329                         }
330
331                         paused.signal();
332                 }
333         }
334
335         pthread_exit_pbd (0);
336         /*NOTREACHED*/
337         return (0);
338 }
339
340 void
341 Butler::schedule_transport_work ()
342 {
343         g_atomic_int_inc (&should_do_transport_work);
344         summon ();
345 }
346
347 void
348 Butler::summon ()
349 {
350         char c = Request::Run;
351         ::write (request_pipe[1], &c, 1);
352 }
353
354 void
355 Butler::stop ()
356 {
357         Glib::Mutex::Lock lm (request_lock);
358         char c = Request::Pause;
359         ::write (request_pipe[1], &c, 1);
360         paused.wait(request_lock);
361 }
362
363 void
364 Butler::wait_until_finished ()
365 {
366         Glib::Mutex::Lock lm (request_lock);
367         char c = Request::Wake;
368         ::write (request_pipe[1], &c, 1);
369         paused.wait(request_lock);
370 }
371
372 bool
373 Butler::transport_work_requested () const
374 {
375         return g_atomic_int_get(&should_do_transport_work);
376 }
377
378 float
379 Butler::read_data_rate () const
380 {
381         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
382            in action. ignore it.
383         */
384         return _read_data_rate > 10485.7600000f ? 0.0f : _read_data_rate;
385 }
386
387 float
388 Butler::write_data_rate () const
389 {
390         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
391            in action. ignore it.
392         */
393         return _write_data_rate > 10485.7600000f ? 0.0f : _write_data_rate;
394 }
395
396 } // namespace ARDOUR