m_sched.c 18.7 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1
2
3
4
5
6
7
8
9
/* Copyright (c) 1997-1999 Miller Puckette.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/*  scheduling stuff  */

#include "m_pd.h"
#include "m_imp.h"
#include "s_stuff.h"
10
#ifdef _WIN32
Miller Puckette's avatar
Miller Puckette committed
11
12
#include <windows.h>
#endif
Miller Puckette's avatar
Miller Puckette committed
13
14
15

    /* LATER consider making this variable.  It's now the LCM of all sample
    rates we expect to see: 32000, 44100, 48000, 88200, 96000. */
16
17
18
19
20
21
#define TIMEUNITPERMSEC (32. * 441.)
#define TIMEUNITPERSECOND (TIMEUNITPERMSEC * 1000.)

#ifndef THREAD_LOCKING
#define THREAD_LOCKING 1
#endif
Miller Puckette's avatar
Miller Puckette committed
22

23
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
24
#include "pthread.h"
25
#endif
Miller Puckette's avatar
Miller Puckette committed
26

27
28
#define SYS_QUIT_QUIT 1
#define SYS_QUIT_RESTART 2
Miller Puckette's avatar
Miller Puckette committed
29
30
31
32
33
34
35
36
37
38
static int sys_quit;

int sys_schedblocksize = DEFDACBLKSIZE;
int sys_usecsincelastsleep(void);
int sys_sleepgrain;

typedef void (*t_clockmethod)(void *client);

struct _clock
{
39
    double c_settime;       /* in TIMEUNITS; <0 if unset */
Miller Puckette's avatar
Miller Puckette committed
40
41
42
    void *c_owner;
    t_clockmethod c_fn;
    struct _clock *c_next;
43
    t_float c_unit;         /* >0 if in TIMEUNITS; <0 if in samples */
Miller Puckette's avatar
Miller Puckette committed
44
45
};

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
46
#ifdef HAVE_UNISTD_H
Miller Puckette's avatar
Miller Puckette committed
47
48
49
50
51
52
53
54
55
56
#include <unistd.h>
#endif

t_clock *clock_new(void *owner, t_method fn)
{
    t_clock *x = (t_clock *)getbytes(sizeof *x);
    x->c_settime = -1;
    x->c_owner = owner;
    x->c_fn = (t_clockmethod)fn;
    x->c_next = 0;
57
    x->c_unit = TIMEUNITPERMSEC;
Miller Puckette's avatar
Miller Puckette committed
58
59
60
61
62
63
64
    return (x);
}

void clock_unset(t_clock *x)
{
    if (x->c_settime >= 0)
    {
65
66
        if (x == pd_this->pd_clock_setlist)
            pd_this->pd_clock_setlist = x->c_next;
Miller Puckette's avatar
Miller Puckette committed
67
68
        else
        {
69
70
71
            t_clock *x2 = pd_this->pd_clock_setlist;
            while (x2->c_next != x) x2 = x2->c_next;
            x2->c_next = x->c_next;
Miller Puckette's avatar
Miller Puckette committed
72
73
74
75
76
77
78
79
        }
        x->c_settime = -1;
    }
}

    /* set the clock to call back at an absolute system time */
void clock_set(t_clock *x, double setticks)
{
80
    if (setticks < pd_this->pd_systime) setticks = pd_this->pd_systime;
Miller Puckette's avatar
Miller Puckette committed
81
82
    clock_unset(x);
    x->c_settime = setticks;
83
84
    if (pd_this->pd_clock_setlist &&
        pd_this->pd_clock_setlist->c_settime <= setticks)
Miller Puckette's avatar
Miller Puckette committed
85
86
    {
        t_clock *cbefore, *cafter;
87
88
89
        for (cbefore = pd_this->pd_clock_setlist,
            cafter = pd_this->pd_clock_setlist->c_next;
                cbefore; cbefore = cafter, cafter = cbefore->c_next)
Miller Puckette's avatar
Miller Puckette committed
90
91
92
93
94
95
96
97
98
        {
            if (!cafter || cafter->c_settime > setticks)
            {
                cbefore->c_next = x;
                x->c_next = cafter;
                return;
            }
        }
    }
99
    else x->c_next = pd_this->pd_clock_setlist, pd_this->pd_clock_setlist = x;
Miller Puckette's avatar
Miller Puckette committed
100
101
102
103
104
}

    /* set the clock to call back after a delay in msec */
void clock_delay(t_clock *x, double delaytime)
{
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    clock_set(x, (x->c_unit > 0 ?
        pd_this->pd_systime + x->c_unit * delaytime :
            pd_this->pd_systime - (x->c_unit*(TIMEUNITPERSECOND/sys_dacsr)) * delaytime));
}

    /* set the time unit in msec or (if 'samps' is set) in samples.  This
    is flagged by setting c_unit negative.  If the clock is currently set,
    recalculate the delay based on the new unit and reschedule */
void clock_setunit(t_clock *x, double timeunit, int sampflag)
{
    double timeleft;
    if (timeunit <= 0)
        timeunit = 1;
    /* if no change, return to avoid truncation errors recalculating delay */
    if ((sampflag && (timeunit == -x->c_unit)) ||
        (!sampflag && (timeunit == x->c_unit * TIMEUNITPERMSEC)))
            return;

        /* figure out time left in the units we were in */
    timeleft = (x->c_settime < 0 ? -1 :
        (x->c_settime - pd_this->pd_systime)/((x->c_unit > 0)? x->c_unit :
            (x->c_unit*(TIMEUNITPERSECOND/sys_dacsr))));
    if (sampflag)
        x->c_unit = -timeunit;  /* negate to flag sample-based */
    else x->c_unit = timeunit * TIMEUNITPERMSEC;
    if (timeleft >= 0)  /* reschedule if already set */
        clock_delay(x, timeleft);
Miller Puckette's avatar
Miller Puckette committed
132
133
134
}

    /* get current logical time.  We don't specify what units this is in;
135
    use clock_gettimesince() to measure intervals from time of this call. */
Miller Puckette's avatar
Miller Puckette committed
136
137
double clock_getlogicaltime( void)
{
138
    return (pd_this->pd_systime);
Miller Puckette's avatar
Miller Puckette committed
139
}
140
141
142

    /* OBSOLETE (misleading) function name kept for compatibility */
double clock_getsystime( void) { return (pd_this->pd_systime); }
Miller Puckette's avatar
Miller Puckette committed
143
144
145
146

    /* elapsed time in milliseconds since the given system time */
double clock_gettimesince(double prevsystime)
{
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    return ((pd_this->pd_systime - prevsystime)/TIMEUNITPERMSEC);
}

    /* elapsed time in units, ala clock_setunit(), since given system time */
double clock_gettimesincewithunits(double prevsystime,
    double units, int sampflag)
{
            /* If in samples, divide TIMEUNITPERSECOND/sys_dacsr first (at
            cost of an extra division) since it's probably an integer and if
            units == 1 and (sys_time - prevsystime) is an integer number of
            DSP ticks, the result will be exact. */
    if (sampflag)
        return ((pd_this->pd_systime - prevsystime)/
            ((TIMEUNITPERSECOND/sys_dacsr)*units));
    else return ((pd_this->pd_systime - prevsystime)/(TIMEUNITPERMSEC*units));
Miller Puckette's avatar
Miller Puckette committed
162
163
164
165
166
}

    /* what value the system clock will have after a delay */
double clock_getsystimeafter(double delaytime)
{
167
    return (pd_this->pd_systime + TIMEUNITPERMSEC * delaytime);
Miller Puckette's avatar
Miller Puckette committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
}

void clock_free(t_clock *x)
{
    clock_unset(x);
    freebytes(x, sizeof *x);
}

/* the following routines maintain a real-execution-time histogram of the
various phases of real-time execution. */

static int sys_bin[] = {0, 2, 5, 10, 20, 30, 50, 100, 1000};
#define NBIN (sizeof(sys_bin)/sizeof(*sys_bin))
#define NHIST 10
static int sys_histogram[NHIST][NBIN];
static double sys_histtime;
static int sched_diddsp, sched_didpoll, sched_didnothing;

void sys_clearhist( void)
{
    unsigned int i, j;
    for (i = 0; i < NHIST; i++)
        for (j = 0; j < NBIN; j++) sys_histogram[i][j] = 0;
    sys_histtime = sys_getrealtime();
    sched_diddsp = sched_didpoll = sched_didnothing = 0;
}

void sys_printhist( void)
{
    unsigned int i, j;
    for (i = 0; i < NHIST; i++)
    {
        int doit = 0;
        for (j = 0; j < NBIN; j++) if (sys_histogram[i][j]) doit = 1;
        if (doit)
        {
            post("%2d %8d %8d %8d %8d %8d %8d %8d %8d", i,
                sys_histogram[i][0],
                sys_histogram[i][1],
                sys_histogram[i][2],
                sys_histogram[i][3],
                sys_histogram[i][4],
                sys_histogram[i][5],
                sys_histogram[i][6],
                sys_histogram[i][7]);
        }
    }
    post("dsp %d, pollgui %d, nothing %d",
        sched_diddsp, sched_didpoll, sched_didnothing);
}

static int sys_histphase;

int sys_addhist(int phase)
{
223
    int j, phasewas = sys_histphase;
Miller Puckette's avatar
Miller Puckette committed
224
225
226
227
    double newtime = sys_getrealtime();
    int msec = (newtime - sys_histtime) * 1000.;
    for (j = NBIN-1; j >= 0; j--)
    {
228
        if (msec >= sys_bin[j])
Miller Puckette's avatar
Miller Puckette committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        {
            sys_histogram[phasewas][j]++;
            break;
        }
    }
    sys_histtime = newtime;
    sys_histphase = phase;
    return (phasewas);
}

#define NRESYNC 20

typedef struct _resync
{
    int r_ntick;
    int r_error;
} t_resync;

static int oss_resyncphase = 0;
static int oss_nresync = 0;
static t_resync oss_resync[NRESYNC];


static char *(oss_errornames[]) = {
"unknown",
"ADC blocked",
"DAC blocked",
"A/D/A sync",
"data late"
};

void glob_audiostatus(void)
{
262
    int nresync, nresyncphase, i;
Miller Puckette's avatar
Miller Puckette committed
263
264
265
266
267
268
269
270
271
272
273
274
    nresync = (oss_nresync >= NRESYNC ? NRESYNC : oss_nresync);
    nresyncphase = oss_resyncphase - 1;
    post("audio I/O error history:");
    post("seconds ago\terror type");
    for (i = 0; i < nresync; i++)
    {
        int errtype;
        if (nresyncphase < 0)
            nresyncphase += NRESYNC;
        errtype = oss_resync[nresyncphase].r_error;
        if (errtype < 0 || errtype > 4)
            errtype = 0;
275

Miller Puckette's avatar
Miller Puckette committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
        post("%9.2f\t%s",
            (sched_diddsp - oss_resync[nresyncphase].r_ntick)
                * ((double)sys_schedblocksize) / sys_dacsr,
            oss_errornames[errtype]);
        nresyncphase--;
    }
}

static int sched_diored;
static int sched_dioredtime;
static int sched_meterson;

void sys_log_error(int type)
{
    oss_resync[oss_resyncphase].r_ntick = sched_diddsp;
    oss_resync[oss_resyncphase].r_error = type;
    oss_nresync++;
    if (++oss_resyncphase == NRESYNC) oss_resyncphase = 0;
    if (type != ERR_NOTHING && !sched_diored &&
        (sched_diddsp >= sched_dioredtime))
    {
297
298
299
        // XXXFIXME
        //sys_vgui("pdtk_pd_dio 1\n");
        error("audio I/O dropout");
Miller Puckette's avatar
Miller Puckette committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        sched_diored = 1;
    }
    sched_dioredtime =
        sched_diddsp + (int)(sys_dacsr /(double)sys_schedblocksize);
}

static int sched_lastinclip, sched_lastoutclip,
    sched_lastindb, sched_lastoutdb;

void glob_watchdog(t_pd *dummy);

static void sched_pollformeters( void)
{
    int inclip, outclip, indb, outdb;
    static int sched_nextmeterpolltime, sched_nextpingtime;
315
    extern int sys_gui_busy;
Miller Puckette's avatar
Miller Puckette committed
316
317
318

        /* if there's no GUI but we're running in "realtime", here is
        where we arrange to ping the watchdog every 2 seconds. */
319
#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__GNU__)
320
    if ((sys_nogui||sys_gui_busy) && sys_hipriority && (sched_diddsp - sched_nextpingtime > 0))
Miller Puckette's avatar
Miller Puckette committed
321
322
323
324
325
326
327
328
    {
        glob_watchdog(0);
            /* ping every 2 seconds */
        sched_nextpingtime = sched_diddsp +
            2 * (int)(sys_dacsr /(double)sys_schedblocksize);
    }
#endif

329
330
    if (sched_diddsp - sched_nextmeterpolltime < 0)
        return;
Miller Puckette's avatar
Miller Puckette committed
331
332
    if (sched_diored && (sched_diddsp - sched_dioredtime > 0))
    {
333
334
        // XXXFIXME
        //sys_vgui("pdtk_pd_dio 0\n");
Miller Puckette's avatar
Miller Puckette committed
335
336
337
338
        sched_diored = 0;
    }
    if (sched_meterson)
    {
339
        t_sample inmax, outmax;
Miller Puckette's avatar
Miller Puckette committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
        sys_getmeters(&inmax, &outmax);
        indb = 0.5 + rmstodb(inmax);
        outdb = 0.5 + rmstodb(outmax);
        inclip = (inmax > 0.999);
        outclip = (outmax >= 1.0);
    }
    else
    {
        indb = outdb = 0;
        inclip = outclip = 0;
    }
    if (inclip != sched_lastinclip || outclip != sched_lastoutclip
        || indb != sched_lastindb || outdb != sched_lastoutdb)
    {
354
355
        // XXXFIXME
        //sys_vgui("pdtk_pd_meters %d %d %d %d\n", indb, outdb, inclip, outclip);
Miller Puckette's avatar
Miller Puckette committed
356
357
358
359
360
361
362
363
364
        sched_lastinclip = inclip;
        sched_lastoutclip = outclip;
        sched_lastindb = indb;
        sched_lastoutdb = outdb;
    }
    sched_nextmeterpolltime =
        sched_diddsp + (int)(sys_dacsr /(double)sys_schedblocksize);
}

365
void glob_meters(void *dummy, t_float f)
Miller Puckette's avatar
Miller Puckette committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
{
    if (f == 0)
        sys_getmeters(0, 0);
    sched_meterson = (f != 0);
    sched_lastinclip = sched_lastoutclip = sched_lastindb = sched_lastoutdb =
        -1;
}

#if 0
void glob_foo(void *dummy, t_symbol *s, int argc, t_atom *argv)
{
    if (argc) sys_clearhist();
    else sys_printhist();
}
#endif

void dsp_tick(void);

384
static int sched_useaudio = SCHED_AUDIO_NONE;
Miller Puckette's avatar
Miller Puckette committed
385
386
387
static double sched_referencerealtime, sched_referencelogicaltime;
double sys_time_per_dsp_tick;

388
389
390
391
392
void sched_reopenmeplease(void)   /* request from s_audio for deferred reopen */
{
    sys_quit = SYS_QUIT_RESTART;
}

393
void sched_set_using_audio(int flag)
Miller Puckette's avatar
Miller Puckette committed
394
{
395
396
    sched_useaudio = flag;
    if (flag == SCHED_AUDIO_NONE)
Miller Puckette's avatar
Miller Puckette committed
397
398
399
400
    {
        sched_referencerealtime = sys_getrealtime();
        sched_referencelogicaltime = clock_getlogicaltime();
    }
Miller Puckette's avatar
Miller Puckette committed
401
402
        if (flag == SCHED_AUDIO_CALLBACK &&
            sched_useaudio != SCHED_AUDIO_CALLBACK)
Miller Puckette's avatar
Miller Puckette committed
403
                sys_quit = SYS_QUIT_RESTART;
Miller Puckette's avatar
Miller Puckette committed
404
405
406
407
        if (flag != SCHED_AUDIO_CALLBACK &&
            sched_useaudio == SCHED_AUDIO_CALLBACK)
                post("sorry, can't turn off callbacks yet; restart Pd");
                    /* not right yet! */
408

409
410
    // XXXFIXME
    //sys_vgui("pdtk_pd_dsp %s\n", flag ? "on" : "off");
Miller Puckette's avatar
Miller Puckette committed
411
412
413
}

    /* take the scheduler forward one DSP tick, also handling clock timeouts */
414
void sched_tick( void)
Miller Puckette's avatar
Miller Puckette committed
415
{
416
417
    double next_sys_time = pd_this->pd_systime +
        (sys_schedblocksize / sys_dacsr) * TIMEUNITPERSECOND;
Miller Puckette's avatar
Miller Puckette committed
418
    int countdown = 5000;
419
420
    while (pd_this->pd_clock_setlist &&
        pd_this->pd_clock_setlist->c_settime < next_sys_time)
Miller Puckette's avatar
Miller Puckette committed
421
    {
422
423
424
        t_clock *c = pd_this->pd_clock_setlist;
        pd_this->pd_systime = c->c_settime;
        clock_unset(pd_this->pd_clock_setlist);
Miller Puckette's avatar
Miller Puckette committed
425
426
427
428
429
430
431
432
433
434
        outlet_setstacklim();
        (*c->c_fn)(c->c_owner);
        if (!countdown--)
        {
            countdown = 5000;
            sys_pollgui();
        }
        if (sys_quit)
            return;
    }
435
    pd_this->pd_systime = next_sys_time;
Miller Puckette's avatar
Miller Puckette committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    dsp_tick();
    sched_diddsp++;
}

/*
Here is Pd's "main loop."  This routine dispatches clock timeouts and DSP
"ticks" deterministically, and polls for input from MIDI and the GUI.  If
we're left idle we also poll for graphics updates; but these are considered
lower priority than the rest.

The time source is normally the audio I/O subsystem via the "sys_send_dacs()"
call.  This call returns true if samples were transferred; false means that
the audio I/O system is still busy with previous transfers.
*/

void sys_pollmidiqueue( void);
void sys_initmidiqueue( void);

 /* sys_idlehook is a hook the user can fill in to grab idle time.  Return
nonzero if you actually used the time; otherwise we're really really idle and
will now sleep. */
int (*sys_idlehook)(void);

459
static void m_pollingscheduler( void)
Miller Puckette's avatar
Miller Puckette committed
460
461
{
    int idlecount = 0;
462
    /* delete this when I'm sure it's not needed for back compatibilty? */
463
    sys_time_per_dsp_tick = (TIMEUNITPERSECOND) *
Miller Puckette's avatar
Miller Puckette committed
464
465
        ((double)sys_schedblocksize) / sys_dacsr;

466
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
        sys_lock();
#endif

    sys_clearhist();
    if (sys_sleepgrain < 100)
        sys_sleepgrain = sys_schedadvance/4;
    if (sys_sleepgrain < 100)
        sys_sleepgrain = 100;
    else if (sys_sleepgrain > 5000)
        sys_sleepgrain = 5000;
    sys_initmidiqueue();
    while (!sys_quit)
    {
        int didsomething = 0;
        int timeforward;

        sys_addhist(0);
    waitfortick:
485
        if (sched_useaudio != SCHED_AUDIO_NONE)
Miller Puckette's avatar
Miller Puckette committed
486
        {
487
488
489
#if THREAD_LOCKING
            /* T.Grill - send_dacs may sleep ->
                unlock thread lock make that time available
Miller Puckette's avatar
Miller Puckette committed
490
491
492
493
494
                - could messaging do any harm while sys_send_dacs is running?
            */
            sys_unlock();
#endif
            timeforward = sys_send_dacs();
495
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
496
            /* T.Grill - done */
497
            sys_lock();
Miller Puckette's avatar
Miller Puckette committed
498
499
500
501
502
503
504
505
506
507
#endif
                /* if dacs remain "idle" for 1 sec, they're hung up. */
            if (timeforward != 0)
                idlecount = 0;
            else
            {
                idlecount++;
                if (!(idlecount & 31))
                {
                    static double idletime;
Miller Puckette's avatar
Miller Puckette committed
508
509
510
511
512
                    if (sched_useaudio != SCHED_AUDIO_POLL)
                    {
                            bug("m_pollingscheduler\n");
                            return;
                    }
Miller Puckette's avatar
Miller Puckette committed
513
514
515
516
517
518
                        /* on 32nd idle, start a clock watch;  every
                        32 ensuing idles, check it */
                    if (idlecount == 32)
                        idletime = sys_getrealtime();
                    else if (sys_getrealtime() - idletime > 1.)
                    {
519
                        error("audio I/O stuck... closing audio");
Miller Puckette's avatar
Miller Puckette committed
520
                        sys_close_audio();
521
                        sched_set_using_audio(SCHED_AUDIO_NONE);
Miller Puckette's avatar
Miller Puckette committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
                        goto waitfortick;
                    }
                }
            }
        }
        else
        {
            if (1000. * (sys_getrealtime() - sched_referencerealtime)
                > clock_gettimesince(sched_referencelogicaltime))
                    timeforward = SENDDACS_YES;
            else timeforward = SENDDACS_NO;
        }
        sys_setmiditimediff(0, 1e-6 * sys_schedadvance);
        sys_addhist(1);
        if (timeforward != SENDDACS_NO)
537
            sched_tick();
Miller Puckette's avatar
Miller Puckette committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
        if (timeforward == SENDDACS_YES)
            didsomething = 1;

        sys_addhist(2);
        sys_pollmidiqueue();
        if (sys_pollgui())
        {
            if (!didsomething)
                sched_didpoll++;
            didsomething = 1;
        }
        sys_addhist(3);
            /* test for idle; if so, do graphics updates. */
        if (!didsomething)
        {
            sched_pollformeters();
            sys_reportidle();
555
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
556
557
558
559
560
561
562
563
564
            sys_unlock();   /* unlock while we idle */
#endif
                /* call externally installed idle function if any. */
            if (!sys_idlehook || !sys_idlehook())
            {
                    /* if even that had nothing to do, sleep. */
                if (timeforward != SENDDACS_SLEPT)
                    sys_microsleep(sys_sleepgrain);
            }
565
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
566
567
568
569
570
571
572
            sys_lock();
#endif
            sys_addhist(5);
            sched_didnothing++;
        }
    }

573
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
574
575
    sys_unlock();
#endif
576
}
Miller Puckette's avatar
Miller Puckette committed
577

578
579
void sched_audio_callbackfn(void)
{
580
    sys_lock();
581
582
    sys_setmiditimediff(0, 1e-6 * sys_schedadvance);
    sys_addhist(1);
583
    sched_tick();
584
585
586
587
588
589
590
    sys_addhist(2);
    sys_pollmidiqueue();
    sys_addhist(3);
    sys_pollgui();
    sys_addhist(5);
    sched_pollformeters();
    sys_addhist(0);
591
    sys_unlock();
592
593
594
595
596
}

static void m_callbackscheduler(void)
{
    sys_initmidiqueue();
Miller Puckette's avatar
Miller Puckette committed
597
    while (!sys_quit)
598
    {
599
600
601
        double timewas = pd_this->pd_systime;
#ifdef _WIN32
        Sleep(1000);
Miller Puckette's avatar
Miller Puckette committed
602
#else
Miller Puckette's avatar
detab    
Miller Puckette committed
603
        sleep(1);
Miller Puckette's avatar
Miller Puckette committed
604
#endif
605
606
607
608
609
610
611
        if (pd_this->pd_systime == timewas)
        {
            sys_lock();
            sys_pollgui();
            sched_tick();
            sys_unlock();
        }
612
613
614
        if (sys_idlehook)
            sys_idlehook();
    }
Miller Puckette's avatar
Miller Puckette committed
615
616
}

617
618
619
620
621
622
623
int m_mainloop(void)
{
    while (sys_quit != SYS_QUIT_QUIT)
    {
        if (sched_useaudio == SCHED_AUDIO_CALLBACK)
            m_callbackscheduler();
        else m_pollingscheduler();
Miller Puckette's avatar
Miller Puckette committed
624
625
626
        if (sys_quit == SYS_QUIT_RESTART)
        {
            sys_quit = 0;
627
628
629
630
631
            if (audio_isopen())
            {
                sys_close_audio();
                sys_reopen_audio();
            }
Miller Puckette's avatar
Miller Puckette committed
632
        }
633
634
635
    }
    return (0);
}
Miller Puckette's avatar
Miller Puckette committed
636

Miller Puckette's avatar
Miller Puckette committed
637
638
639
int m_batchmain(void)
{
    while (sys_quit != SYS_QUIT_QUIT)
640
        sched_tick();
Miller Puckette's avatar
Miller Puckette committed
641
642
643
    return (0);
}

Miller Puckette's avatar
Miller Puckette committed
644
645
/* ------------ thread locking ------------------- */

646
#if THREAD_LOCKING
Miller Puckette's avatar
Miller Puckette committed
647
static pthread_mutex_t sys_mutex = PTHREAD_MUTEX_INITIALIZER;
648
static int sys_mutex_lock = 0;
Miller Puckette's avatar
Miller Puckette committed
649
650
651

void sys_lock(void)
{
652
653
654
    //fprintf(stderr,"sys_lock\n");
    if (!sys_mutex_lock)
    {
655
656
657
658
        int res = pthread_mutex_lock(&sys_mutex);
        //fprintf(stderr,"lock %d\n", res);
        if (!res)
            sys_mutex_lock = 1;
659
    }
Miller Puckette's avatar
Miller Puckette committed
660
661
662
663
}

void sys_unlock(void)
{
664
665
    if (sys_mutex_lock)
    {
666
667
668
669
        int res = pthread_mutex_unlock(&sys_mutex);
        //fprintf(stderr,"unlock %d\n", res);
        if (!res)
            sys_mutex_lock = 0;
670
    }
Miller Puckette's avatar
Miller Puckette committed
671
672
673
674
}

int sys_trylock(void)
{
675
676
677
678
679
    int res = pthread_mutex_trylock(&sys_mutex);
    //fprintf(stderr,"trylock %d\n", res);
    if (!res)
        sys_mutex_lock = 1;
    return res;
Miller Puckette's avatar
Miller Puckette committed
680
681
682
683
684
685
}

#else

void sys_lock(void) {}
void sys_unlock(void) {}
686
int sys_trylock(void) {return (1);}
Miller Puckette's avatar
Miller Puckette committed
687
688
689
690
691

#endif

void sys_exit(void)
{
692
    sys_quit = SYS_QUIT_QUIT;
Miller Puckette's avatar
Miller Puckette committed
693
}