module Sound.SC3.Server.NRT where
import Data.Maybe
import qualified Data.ByteString.Lazy as B
import System.FilePath
import System.IO
import System.Process
import Sound.OSC.Core
import Sound.OSC.Coding.Byte
import Sound.SC3.Server.Enum
oscWithSize :: Bundle -> B.ByteString
oscWithSize o =
let b = encodeBundle o
l = encode_i32 (fromIntegral (B.length b))
in B.append l b
data NRT = NRT {nrt_bundles :: [Bundle]} deriving (Show)
nrt_span :: (Time -> Bool) -> NRT -> ([Bundle],[Bundle])
nrt_span f = span (f . bundleTime) . nrt_bundles
encodeNRT :: NRT -> B.ByteString
encodeNRT = B.concat . map oscWithSize . nrt_bundles
writeNRT :: FilePath -> NRT -> IO ()
writeNRT fn = B.writeFile fn . encodeNRT
putNRT :: Handle -> NRT -> IO ()
putNRT h = B.hPut h . encodeNRT
decode_nrt_bundles :: B.ByteString -> [Bundle]
decode_nrt_bundles s =
let (p,q) = B.splitAt 4 s
n = fromIntegral (decode_i32 p)
(r,s') = B.splitAt n q
r' = decodeBundle r
in if B.null s'
then [r']
else r' : decode_nrt_bundles s'
decodeNRT :: B.ByteString -> NRT
decodeNRT = NRT . decode_nrt_bundles
readNRT :: FilePath -> IO NRT
readNRT = fmap decodeNRT . B.readFile
type NRT_Render_Plain = (FilePath,FilePath,Int,Int,SampleFormat)
nrt_render_plain :: NRT_Render_Plain -> NRT -> IO ()
nrt_render_plain (osc_nm,sf_nm,nc,sr,sf) sc = do
let sf_ty = case takeExtension sf_nm of
'.':ext -> let fmt = soundFileFormat_from_extension ext
in fromMaybe (error "nrt_render_plain: unknown sf extension") fmt
_ -> error "nrt_render_plain: invalid sf extension"
sys = unwords ["scsynth"
,"-i","0"
,"-o",show nc
,"-N"
,osc_nm,"_"
,sf_nm,show sr,soundFileFormatString sf_ty,sampleFormatString sf]
writeNRT osc_nm sc
_ <- system sys
return ()