Skip to content

Commit

Permalink
Fix integer underflow/unsigned wrapping.
Browse files Browse the repository at this point in the history
The number of xrun fragments to skip is added once to ctx->jack_xruns but
then subtracted multiple times (once for each stream) from the same variable.
This causes the unsigned int to "underflow" and wrap around.

- Use unsigned int in all calculations instead of mixing un/signed.
- Remove erroneous and useless subtraction logic
- Replace for loop by simple multiplication
- Remove unneeded casts to float
  • Loading branch information
szanni authored and padenot committed Sep 14, 2020
1 parent f39ce8a commit f4c3197
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/cubeb_jack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,9 @@ cbjack_xrun_callback(void * arg)
cubeb * ctx = (cubeb *)arg;

float delay = api_jack_get_xrun_delayed_usecs(ctx->jack_client);
int fragments = (int)ceilf( ((delay / 1000000.0) * ctx->jack_sample_rate )
/ (float)(ctx->jack_buffer_size) );
ctx->jack_xruns += fragments;
float fragments = ceilf(((delay / 1000000.0) * ctx->jack_sample_rate) / ctx->jack_buffer_size);

ctx->jack_xruns += (unsigned int)fragments;
return 0;
}

Expand Down Expand Up @@ -332,9 +332,11 @@ static int
cbjack_process(jack_nframes_t nframes, void * arg)
{
cubeb * ctx = (cubeb *)arg;
int t_jack_xruns = ctx->jack_xruns;
unsigned int t_jack_xruns = ctx->jack_xruns;
int i;

ctx->jack_xruns = 0;

for (int j = 0; j < MAX_STREAMS; j++) {
cubeb_stream *stm = &ctx->streams[j];
float *bufs_out[stm->out_params.channels];
Expand All @@ -344,10 +346,7 @@ cbjack_process(jack_nframes_t nframes, void * arg)
continue;

// handle xruns by skipping audio that should have been played
for (i = 0; i < t_jack_xruns; i++) {
stm->position += ctx->fragment_size * stm->ratio;
}
ctx->jack_xruns -= t_jack_xruns;
stm->position += t_jack_xruns * ctx->fragment_size * stm->ratio;

if (!stm->ports_ready)
continue;
Expand Down

0 comments on commit f4c3197

Please sign in to comment.