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