a) fix special button press handling for solo+mute buttons
[ardour.git] / libs / ardour / session_butler.cc
1 /*
2     Copyright (C) 1999-2002 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     $Id$
19 */
20
21 #include <algorithm>
22 #include <string>
23 #include <cmath>
24 #include <cerrno>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <poll.h>
28
29 #include <pbd/error.h>
30 #include <pbd/lockmonitor.h>
31 #include <pbd/pthread_utils.h>
32
33 #include <ardour/configuration.h>
34 #include <ardour/audioengine.h>
35 #include <ardour/session.h>
36 #include <ardour/diskstream.h>
37 #include <ardour/crossfade.h>
38 #include <ardour/timestamps.h>
39
40 #include "i18n.h"
41
42 using namespace std;
43 using namespace ARDOUR;
44 //using namespace sigc;
45
46 static float _read_data_rate;
47 static float _write_data_rate;
48
49 /* XXX put this in the right place */
50
51 static inline uint32_t next_power_of_two (uint32_t n)
52 {
53         --n;
54         n |= n >> 16;
55         n |= n >> 8;
56         n |= n >> 4;
57         n |= n >> 2;
58         n |= n >> 1;
59         ++n;
60         return n;
61 }
62
63 /*---------------------------------------------------------------------------
64  BUTLER THREAD 
65  ---------------------------------------------------------------------------*/
66
67 int
68 Session::start_butler_thread ()
69 {
70         /* size is in Samples, not bytes */
71
72         dstream_buffer_size = (uint32_t) floor (Config->get_track_buffer_seconds() * (float) frame_rate());
73
74         Crossfade::set_buffer_size (dstream_buffer_size);
75
76         pthread_cond_init (&butler_paused, 0);
77         
78         butler_should_run = false;
79
80         if (pipe (butler_request_pipe)) {
81                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
82                 return -1;
83         }
84
85         if (fcntl (butler_request_pipe[0], F_SETFL, O_NONBLOCK)) {
86                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
87                 return -1;
88         }
89
90         if (fcntl (butler_request_pipe[1], F_SETFL, O_NONBLOCK)) {
91                 error << string_compose(_("UI: cannot set O_NONBLOCK on butler request pipe (%1)"), strerror (errno)) << endmsg;
92                 return -1;
93         }
94
95         if (pthread_create_and_store ("disk butler", &butler_thread, 0, _butler_thread_work, this)) {
96                 error << _("Session: could not create butler thread") << endmsg;
97                 return -1;
98         }
99
100         // pthread_detach (butler_thread);
101
102         return 0;
103 }
104
105 void
106 Session::terminate_butler_thread ()
107 {
108         void* status;
109         char c = ButlerRequest::Quit;
110         ::write (butler_request_pipe[1], &c, 1);
111         pthread_join (butler_thread, &status);
112 }
113
114 void
115 Session::schedule_butler_transport_work ()
116 {
117         atomic_inc (&butler_should_do_transport_work);
118         summon_butler ();
119 }
120
121 void
122 Session::schedule_curve_reallocation ()
123 {
124         post_transport_work = PostTransportWork (post_transport_work | PostTransportCurveRealloc);
125         schedule_butler_transport_work ();
126 }
127
128 void
129 Session::summon_butler ()
130 {
131         char c = ButlerRequest::Run;
132         ::write (butler_request_pipe[1], &c, 1);
133 }
134
135 void
136 Session::stop_butler ()
137 {
138         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
139         char c = ButlerRequest::Pause;
140         ::write (butler_request_pipe[1], &c, 1);
141         pthread_cond_wait (&butler_paused, butler_request_lock.mutex());
142 }
143
144 void
145 Session::wait_till_butler_finished ()
146 {
147         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
148         char c = ButlerRequest::Wake;
149         ::write (butler_request_pipe[1], &c, 1);
150         pthread_cond_wait (&butler_paused, butler_request_lock.mutex());
151 }
152
153 void *
154 Session::_butler_thread_work (void* arg)
155 {
156         PBD::ThreadCreated (pthread_self(), X_("Butler"));
157
158         return ((Session *) arg)->butler_thread_work ();
159         return 0;
160 }
161
162 #define transport_work_requested() atomic_read(&butler_should_do_transport_work)
163
164 void *
165 Session::butler_thread_work ()
166 {
167         uint32_t err = 0;
168         int32_t bytes;
169         bool compute_io;
170         struct timeval begin, end;
171         struct pollfd pfd[1];
172         bool disk_work_outstanding = false;
173         DiskStreamList::iterator i;
174
175         butler_mixdown_buffer = new Sample[DiskStream::disk_io_frames()];
176         butler_gain_buffer = new gain_t[DiskStream::disk_io_frames()];
177         // this buffer is used for temp conversion purposes in filesources
178         char * conv_buffer = conversion_buffer(ButlerContext);
179
180         while (true) {
181
182                 pfd[0].fd = butler_request_pipe[0];
183                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
184                 
185                 if (poll (pfd, 1, (disk_work_outstanding ? 0 : -1)) < 0) {
186                         
187                         if (errno == EINTR) {
188                                 continue;
189                         }
190                         
191                         error << string_compose (_("poll on butler request pipe failed (%1)"),
192                                           strerror (errno))
193                               << endmsg;
194                         break;
195                 }
196
197                 if (pfd[0].revents & ~POLLIN) {
198                         error << _("Error on butler thread request pipe") << endmsg;
199                         break;
200                 }
201                 
202                 if (pfd[0].revents & POLLIN) {
203                         
204                         char req;
205                         
206                         /* empty the pipe of all current requests */
207                         
208                         while (1) {
209                                 size_t nread = ::read (butler_request_pipe[0], &req, sizeof (req));
210                                 
211                                 if (nread == 1) {
212                                         
213                                         switch ((ButlerRequest::Type) req) {
214                                                 
215                                         case ButlerRequest::Wake:
216                                                 break;
217
218                                         case ButlerRequest::Run:
219                                                 butler_should_run = true;
220                                                 break;
221                                                 
222                                         case ButlerRequest::Pause:
223                                                 butler_should_run = false;
224                                                 break;
225                                                 
226                                         case ButlerRequest::Quit:
227                                                 pthread_exit_pbd (0);
228                                                 /*NOTREACHED*/
229                                                 break;
230                                                 
231                                         default:
232                                                 break;
233                                         }
234                                         
235                                 } else if (nread == 0) {
236                                         break;
237                                 } else if (errno == EAGAIN) {
238                                         break;
239                                 } else {
240                                         fatal << _("Error reading from butler request pipe") << endmsg;
241                                         /*NOTREACHED*/
242                                 }
243                         }
244                 }
245         
246                 for (i = diskstreams.begin(); i != diskstreams.end(); ++i) {
247                         // cerr << "BEFORE " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
248                 }
249
250                 if (transport_work_requested()) {
251                         butler_transport_work ();
252                 }
253
254                 disk_work_outstanding = false;
255                 bytes = 0;
256                 compute_io = true;
257
258                 gettimeofday (&begin, 0);
259
260                 RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
261                 
262                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
263                         
264                         // cerr << "rah fondr " << (*i)->io()->name () << endl;
265
266                         switch ((*i)->do_refill (butler_mixdown_buffer, butler_gain_buffer, conv_buffer)) {
267                         case 0:
268                                 bytes += (*i)->read_data_count();
269                                 break;
270                         case 1:
271                                 bytes += (*i)->read_data_count();
272                                 disk_work_outstanding = true;
273                                 break;
274                                 
275                         default:
276                                 compute_io = false;
277                                 error << string_compose(_("Butler read ahead failure on dstream %1"), (*i)->name()) << endmsg;
278                                 break;
279                         }
280
281                 }
282
283                 if (i != diskstreams.end()) {
284                         /* we didn't get to all the streams */
285                         disk_work_outstanding = true;
286                 }
287                 
288                 if (!err && transport_work_requested()) {
289                         continue;
290                 }
291
292                 if (compute_io) {
293                         gettimeofday (&end, 0);
294                         
295                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
296                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
297                         
298                         _read_data_rate = bytes / (e - b);
299                 }
300
301                 bytes = 0;
302                 compute_io = true;
303                 gettimeofday (&begin, 0);
304                 
305                 for (i = diskstreams.begin(); !transport_work_requested() && butler_should_run && i != diskstreams.end(); ++i) {
306                         
307                         // cerr << "write behind for " << (*i)->name () << endl;
308                         
309                         switch ((*i)->do_flush (conv_buffer)) {
310                         case 0:
311                                 bytes += (*i)->write_data_count();
312                                 break;
313                         case 1:
314                                 bytes += (*i)->write_data_count();
315                                 disk_work_outstanding = true;
316                                 break;
317                                 
318                         default:
319                                 err++;
320                                 compute_io = false;
321                                 error << string_compose(_("Butler write-behind failure on dstream %1"), (*i)->name()) << endmsg;
322                                 /* don't break - try to flush all streams in case they 
323                                    are split across disks.
324                                 */
325                         }
326                 }
327
328                 if (err && actively_recording()) {
329                         /* stop the transport and try to catch as much possible
330                            captured state as we can.
331                         */
332                         request_stop ();
333                 }
334
335                 if (i != diskstreams.end()) {
336                         /* we didn't get to all the streams */
337                         disk_work_outstanding = true;
338                 }
339                 
340                 if (!err && transport_work_requested()) {
341                         continue;
342                 }
343
344                 if (compute_io) {
345                         gettimeofday (&end, 0);
346                         
347                         double b = begin.tv_sec  + (begin.tv_usec/1000000.0);
348                         double e = end.tv_sec + (end.tv_usec / 1000000.0);
349                         
350                         _write_data_rate = bytes / (e - b);
351                 }
352                 
353                 if (!disk_work_outstanding) {
354                         refresh_disk_space ();
355                 }
356
357
358                 {
359                         LockMonitor lm (butler_request_lock, __LINE__, __FILE__);
360
361                         if (butler_should_run && (disk_work_outstanding || transport_work_requested())) {
362 //                              for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
363 //                                      cerr << "AFTER " << (*i)->name() << ": pb = " << (*i)->playback_buffer_load() << " cp = " << (*i)->capture_buffer_load() << endl;
364 //                              }
365
366                                 continue;
367                         }
368
369                         pthread_cond_signal (&butler_paused);
370                 }
371         }
372
373         pthread_exit_pbd (0);
374         /*NOTREACHED*/
375         return (0);
376 }
377
378
379 void
380 Session::request_overwrite_buffer (DiskStream* stream)
381 {
382         Event *ev = new Event (Event::Overwrite, Event::Add, Event::Immediate, 0, 0, 0.0);
383         ev->set_ptr (stream);
384         queue_event (ev);
385 }
386
387 void
388 Session::overwrite_some_buffers (DiskStream* ds)
389 {
390         /* executed by the audio thread */
391
392         if (actively_recording()) {
393                 return;
394         }
395
396         if (ds) {
397
398                 ds->set_pending_overwrite (true);
399
400         } else {
401
402                 RWLockMonitor dm (diskstream_lock, false, __LINE__, __FILE__);
403                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
404                         (*i)->set_pending_overwrite (true);
405                 }
406         }
407
408         post_transport_work = PostTransportWork (post_transport_work | PostTransportOverWrite);
409         schedule_butler_transport_work ();
410 }
411
412 float
413 Session::read_data_rate () const
414 {
415         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
416            in action. ignore it.
417         */
418         return _read_data_rate > 10485760000.0f ? 0.0f : _read_data_rate;
419 }
420
421 float
422 Session::write_data_rate () const
423 {
424         /* disk i/o in excess of 10000MB/sec indicate the buffer cache
425            in action. ignore it.
426         */
427         return _write_data_rate > 10485760000.0f ? 0.0f : _write_data_rate;
428 }
429
430 uint32_t
431 Session::playback_load ()
432 {
433         return (uint32_t) atomic_read (&_playback_load);
434 }
435
436 uint32_t
437 Session::capture_load ()
438 {
439         return (uint32_t) atomic_read (&_capture_load);
440 }
441
442 uint32_t
443 Session::playback_load_min ()
444 {
445         return (uint32_t) atomic_read (&_playback_load_min);
446 }
447
448 uint32_t
449 Session::capture_load_min ()
450 {
451         return (uint32_t) atomic_read (&_capture_load_min);
452 }
453
454 void
455 Session::reset_capture_load_min ()
456 {
457         atomic_set (&_capture_load_min, 100);
458 }
459
460
461 void
462 Session::reset_playback_load_min ()
463 {
464         atomic_set (&_playback_load_min, 100);
465 }