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