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