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