changes from 2.X starting in march 2009 through oct 20 2009 (5826 inclusive)
[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         pthread_set_name (X_("butler"));
119         return ((Butler *) arg)->thread_work ();
120 }
121
122 void *
123 Butler::thread_work ()
124 {
125         uint32_t err = 0;
126         int32_t bytes;
127         bool compute_io;
128         microseconds_t begin, end;
129
130         struct pollfd pfd[1];
131         bool disk_work_outstanding = false;
132         Session::DiskstreamList::iterator i;
133
134         while (true) {
135                 pfd[0].fd = request_pipe[0];
136                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
137
138                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
139
140                         if (errno == EINTR) {
141                                 continue;
142                         }
143
144                         error << string_compose (_("poll on butler request pipe failed (%1)"),
145                                           strerror (errno))
146                               << endmsg;
147                         break;
148                 }
149
150                 if (pfd[0].revents & ~POLLIN) {
151                         error << string_compose (_("Error on butler thread request pipe: fd=%1 err=%2"), pfd[0].fd, pfd[0].revents) << endmsg;
152                         break;
153                 }
154
155                 if (pfd[0].revents & POLLIN) {
156
157                         char req;
158
159                         /* empty the pipe of all current requests */
160
161                         while (1) {
162                                 size_t nread = ::read (request_pipe[0], &req, sizeof (req));
163                                 if (nread == 1) {
164
165                                         switch ((Request::Type) req) {
166
167                                         case Request::Wake:
168                                                 break;
169
170                                         case Request::Run:
171                                                 should_run = true;
172                                                 break;
173
174                                         case Request::Pause:
175                                                 should_run = false;
176                                                 break;
177
178                                         case Request::Quit:
179                                                 pthread_exit_pbd (0);
180                                                 /*NOTREACHED*/
181                                                 break;
182
183                                         default:
184                                                 break;
185                                         }
186
187                                 } else if (nread == 0) {
188                                         break;
189                                 } else if (errno == EAGAIN) {
190                                         break;
191                                 } else {
192                                         fatal << _("Error reading from butler request pipe") << endmsg;
193                                         /*NOTREACHED*/
194                                 }
195                         }
196                 }
197
198                 if (transport_work_requested()) {
199                         _session.butler_transport_work ();
200                 }
201
202                 disk_work_outstanding = false;
203                 bytes = 0;
204                 compute_io = true;
205
206                 begin = get_microseconds();
207
208                 boost::shared_ptr<Session::DiskstreamList> dsl = _session.diskstream_list().reader ();
209
210 //              for (i = dsl->begin(); i != dsl->end(); ++i) {
211 //                      cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
212 //              }
213
214                 for (i = dsl->begin(); !transport_work_requested() && should_run && i != dsl->end(); ++i) {
215
216                         boost::shared_ptr<Diskstream> ds = *i;
217
218                         /* don't read inactive tracks */
219
220                         boost::shared_ptr<IO> io = ds->io();
221
222                         if (io && !io->active()) {
223                                 continue;
224                         }
225
226                         switch (ds->do_refill ()) {
227                         case 0:
228                                 bytes += ds->read_data_count();
229                                 break;
230                         case 1:
231                                 bytes += ds->read_data_count();
232                                 disk_work_outstanding = true;
233                                 break;
234
235                         default:
236                                 compute_io = false;
237                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
238                                 break;
239                         }
240
241                 }
242
243                 if (i != dsl->end()) {
244                         /* we didn't get to all the streams */
245                         disk_work_outstanding = true;
246                 }
247
248                 if (!err && transport_work_requested()) {
249                         continue;
250                 }
251
252                 if (compute_io) {
253                         end = get_microseconds();
254                         if (end - begin > 0) {
255                                 _read_data_rate = (float) bytes / (float) (end - begin);
256                         } else {
257                                 _read_data_rate = 0; // infinity better
258                         }
259                 }
260
261                 bytes = 0;
262                 compute_io = true;
263                 begin = get_microseconds();
264
265                 for (i = dsl->begin(); !transport_work_requested() && should_run && i != dsl->end(); ++i) {
266                         // cerr << "write behind for " << (*i)->name () << endl;
267
268                         /* note that we still try to flush diskstreams attached to inactive routes
269                          */
270
271                         switch ((*i)->do_flush (ButlerContext)) {
272                         case 0:
273                                 bytes += (*i)->write_data_count();
274                                 break;
275                         case 1:
276                                 bytes += (*i)->write_data_count();
277                                 disk_work_outstanding = true;
278                                 break;
279
280                         default:
281                                 err++;
282                                 compute_io = false;
283                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
284                                 /* don't break - try to flush all streams in case they
285                                    are split across disks.
286                                 */
287                         }
288                 }
289
290                 if (err && _session.actively_recording()) {
291                         /* stop the transport and try to catch as much possible
292                            captured state as we can.
293                         */
294                         _session.request_stop ();
295                 }
296
297                 if (i != dsl->end()) {
298                         /* we didn't get to all the streams */
299                         disk_work_outstanding = true;
300                 }
301
302                 if (!err && transport_work_requested()) {
303                         continue;
304                 }
305
306                 if (compute_io) {
307                         // there are no apparent users for this calculation?
308                         end = get_microseconds();
309                         if (end - begin > 0) {
310                                 _write_data_rate = (float) bytes / (float) (end - begin);
311                         } else {
312                                 _write_data_rate = 0; // Well, infinity would be better
313                         }
314                 }
315
316                 if (!disk_work_outstanding) {
317                         _session.refresh_disk_space ();
318                 }
319
320
321                 {
322                         Glib::Mutex::Lock lm (request_lock);
323
324                         if (should_run && (disk_work_outstanding || transport_work_requested())) {
325 //                              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
326 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
327 //                              }
328
329                                 continue;
330                         }
331
332                         paused.signal();
333                 }
334         }
335
336         pthread_exit_pbd (0);
337         /*NOTREACHED*/
338         return (0);
339 }
340
341 void
342 Butler::schedule_transport_work ()
343 {
344         g_atomic_int_inc (&should_do_transport_work);
345         summon ();
346 }
347
348 void
349 Butler::summon ()
350 {
351         char c = Request::Run;
352         ::write (request_pipe[1], &c, 1);
353 }
354
355 void
356 Butler::stop ()
357 {
358         Glib::Mutex::Lock lm (request_lock);
359         char c = Request::Pause;
360         ::write (request_pipe[1], &c, 1);
361         paused.wait(request_lock);
362 }
363
364 void
365 Butler::wait_until_finished ()
366 {
367         Glib::Mutex::Lock lm (request_lock);
368         char c = Request::Wake;
369         ::write (request_pipe[1], &c, 1);
370         paused.wait(request_lock);
371 }
372
373 bool
374 Butler::transport_work_requested () const
375 {
376         return g_atomic_int_get(&should_do_transport_work);
377 }
378
379 float
380 Butler::read_data_rate () const
381 {
382         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
383            in action. ignore it.
384         */
385         return _read_data_rate > 10485.7600000f ? 0.0f : _read_data_rate;
386 }
387
388 float
389 Butler::write_data_rate () const
390 {
391         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
392            in action. ignore it.
393         */
394         return _write_data_rate > 10485.7600000f ? 0.0f : _write_data_rate;
395 }
396
397 } // namespace ARDOUR