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