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