]> git.alsa-project.org Git - alsa-lib.git/commitdiff
rawmidi: allocate the read buffer in the params call
authorJaroslav Kysela <perex@perex.cz>
Mon, 11 Oct 2021 12:33:29 +0000 (14:33 +0200)
committerJaroslav Kysela <perex@perex.cz>
Thu, 28 Oct 2021 06:40:20 +0000 (08:40 +0200)
It is better to allocate the read buffer for the framing stream
in the params setup call.

Suggested-by: David Henningsson <coding@diwic.se>
Signed-off-by: Jaroslav Kysela <perex@perex.cz>
src/rawmidi/rawmidi_hw.c

index 9ffa31992607f4f0066f66b5e4215247f5b7070a..e5bb3ee3b31c10167bdf9ad7bc2136eac9cd3456 100644 (file)
@@ -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)