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