haskell-game / sdl2

Haskell bindings to the SDL2 library
Other
363 stars 86 forks source link

Random segfaults with basic audio code #219

Open mlugg opened 4 years ago

mlugg commented 4 years ago

Hi, I'm trying to use the SDL 2 bindings to play basic audio, and am encountering some odd errors. I have a small test program which is quite similar to AudioExample, but I'm having random crashes on it. My source code is below. The errors are not consistent; sometimes the audio will play for a second and the program will gracefully exit as expected, other times it segfaults partway through, and occasionally I get GHC errors like the following:

audio: internal error: scavenge: unimplemented/strange closure type 4325385 @ 0x42001f7530 (GHC version 8.6.5 for x86_64_unknown_linux) Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug Aborted

Note that if I replace take n wave in the following code with something like replicate n 128, the program does not crash.

{-# LANGUAGE GADTs #-}

module Main where

import Control.Concurrent
import Data.IORef
import Data.Word
import Data.Functor
import Control.Monad
import SDL.Audio
import SDL.Init
import qualified Data.Vector.Storable.Mutable as V
import qualified Data.Vector as V'

-- should be a 50Hz sine wave
w :: [Word8]
w = [0..] <&> \x -> floor $ 127 * (sin (50 * x / (44100::Float) * 2*pi) + 1)

cb :: IORef [Word8] -> AudioFormat a -> V.IOVector a -> IO ()

-- For some reason we get this rather than the requested Signed8BitAudio?

cb waveRef Unsigned8BitAudio vec = do
  wave <- readIORef waveRef
  let n = V.length vec
  zipWithM_
    (V.write vec)
    [0..]
    (take n wave)
  writeIORef waveRef (drop n wave)

main :: IO ()
main =
  newIORef w >>= \waveRef ->
  initializeAll *>
  openAudioDevice (
    OpenDeviceSpec
      (Mandate 44100)
      (Mandate Signed8BitAudio)
      (Mandate Mono)
      8192
      (cb waveRef)
      ForPlayback
      Nothing
  ) >>= \(dev, _) ->
  setAudioDevicePlaybackState dev Play *>
  threadDelay 1000000 *>
  closeAudioDevice dev

I have not tested the actual AudioExample example code on my system yet; I'll do that shortly and update this issue with the results.

mlugg commented 4 years ago

I do get the same behaviour from the AudioExample.hs example

dpwiz commented 2 years ago

Works on Ubuntu 21.10. GHC 8.10 through 9.2.

I can't hear the 50hz 8bit sine, but the other tones sound fine and no crashes.

AudioExample works too.

dpwiz commented 2 years ago

For some reason we get this rather than the requested Signed8BitAudio?

I get Signed8Bit (and had to change element type to Int8).