From a6a22d82a068be01b0cabb9d87189b993c6a0fc5 Mon Sep 17 00:00:00 2001 From: Jaroslav Kysela Date: Mon, 11 Oct 2021 14:33:29 +0200 Subject: [PATCH] rawmidi: allocate the read buffer in the params call It is better to allocate the read buffer for the framing stream in the params setup call. Suggested-by: David Henningsson Signed-off-by: Jaroslav Kysela --- src/rawmidi/rawmidi_hw.c | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/rawmidi/rawmidi_hw.c b/src/rawmidi/rawmidi_hw.c index 9ffa3199..e5bb3ee3 100644 --- a/src/rawmidi/rawmidi_hw.c +++ b/src/rawmidi/rawmidi_hw.c @@ -108,17 +108,32 @@ static int snd_rawmidi_hw_info(snd_rawmidi_t *rmidi, snd_rawmidi_info_t * info) static int snd_rawmidi_hw_params(snd_rawmidi_t *rmidi, snd_rawmidi_params_t * params) { snd_rawmidi_hw_t *hw = rmidi->private_data; + int tstamp; params->stream = rmidi->stream; if (ioctl(hw->fd, SNDRV_RAWMIDI_IOCTL_PARAMS, params) < 0) { SYSERR("SNDRV_RAWMIDI_IOCTL_PARAMS failed"); return -errno; } buf_reset(hw); - if (hw->buf && - ((params->mode & SNDRV_RAWMIDI_MODE_FRAMING_MASK) != SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP)) { + tstamp = (params->mode & SNDRV_RAWMIDI_MODE_FRAMING_MASK) == SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP; + if (hw->buf && !tstamp) { free(hw->buf); hw->buf = NULL; hw->buf_size = 0; + } else if (tstamp) { + size_t alloc_size; + void *buf; + + alloc_size = page_size(); + if (params->buffer_size > alloc_size) + alloc_size = params->buffer_size; + if (alloc_size != hw->buf_size) { + buf = realloc(hw->buf, alloc_size); + if (buf == NULL) + return -ENOMEM; + hw->buf = buf; + hw->buf_size = alloc_size; + } } return 0; } @@ -230,7 +245,6 @@ static ssize_t snd_rawmidi_hw_tread(snd_rawmidi_t *rmidi, struct timespec *tstam { snd_rawmidi_hw_t *hw = rmidi->private_data; ssize_t result = 0, ret; - size_t alloc_size; /* no timestamp */ tstamp->tv_sec = tstamp->tv_nsec = 0; @@ -245,15 +259,6 @@ static ssize_t snd_rawmidi_hw_tread(snd_rawmidi_t *rmidi, struct timespec *tstam size -= result; } - alloc_size = page_align(size * 2); /* keep room for the frame meta data */ - if (alloc_size > hw->buf_size) { - void *buf = realloc(hw->buf, alloc_size); - if (buf == NULL) - return result > 0 ? result : -ENOMEM; - hw->buf = buf; - hw->buf_size = alloc_size; - } - buf_reset(hw); ret = read(hw->fd, hw->buf, hw->buf_size); if (ret < 0) -- 2.47.3