3 , ExistentialQuantification
6 -- | WavPack metadata sub-blocks
7 module Codec.Audio.WavPack.Metadata
17 import Data.Binary.Get
18 import Data.Binary.Put
20 import qualified Data.ByteString.Lazy as L
22 import Prelude.Unicode
24 -- | Type class for every metadata sub-blocks.
25 class (Binary α, Eq α, Show α, Typeable α) ⇒ Metadata α where
26 -- | Get the metadata ID (mandatory).
28 -- | Get the size of metadata (optional).
30 metaSize = fromIntegral ∘ L.length ∘ runPut ∘ put
31 -- | Cast a 'SubBlock' to this type of metadata (optional).
32 fromSubBlock ∷ SubBlock → Maybe α
33 fromSubBlock (SubBlock a) = cast a
34 -- | Wrap the metadata into 'SubBlock' (optional).
35 toSubBlock ∷ α → SubBlock
38 -- | An opaque sub-block container.
39 data SubBlock = ∀α. Metadata α ⇒ SubBlock α
42 instance Metadata SubBlock where
43 metaID (SubBlock a) = metaID a
44 metaSize (SubBlock a) = metaSize a
48 instance Binary SubBlock where
50 = let size = metaSize a
51 oddBit = if odd size then 0x40 else 0
52 largeBit = if size > 255 then 0x80 else 0
53 idWord = metaID a .|. oddBit .|. largeBit
57 -- Don't forget about the endianness.
58 do putWord8 $ fromIntegral $ (size `shiftR` 1) .&. 0xFF
59 putWord8 $ fromIntegral $ (size `shiftR` 9) .&. 0xFF
60 putWord8 $ fromIntegral $ (size `shiftR` 17) .&. 0xFF
62 putWord8 $ fromIntegral $ (size `shiftR` 1) .&. 0xFF
64 when (odd size) $ putWord8 0
66 get = do idWord ← getWord8
67 let isOdd = idWord .&. 0x40 ≢ 0
68 isLarge = idWord .&. 0x80 ≢ 0
69 rawID = idWord .&. (complement 0x40) .&. (complement 0x80)
70 adj = if isOdd then -1 else 0
71 size ← if isLarge then
75 return $ ( (fromIntegral sz2 `shiftL` 17) .|.
76 (fromIntegral sz1 `shiftL` 9) .|.
77 (fromIntegral sz0 `shiftL` 1)
80 fmap ((+ adj) ∘ (`shiftL` 1) ∘ fromIntegral) getWord8
81 subb ← getLazyByteString $ fromIntegral (size ∷ Word32)
82 return $ runGet (getSubBlock rawID) subb
84 getSubBlock ∷ Word8 → Get SubBlock
85 getSubBlock 0x00 = fmap SubBlock (get ∷ Get Dummy)
87 = if unknownID .&. 0x20 ≡ 0 then
88 fail ("Unknown WavPack metadata ID: " ⧺ show unknownID)
90 -- It's unknown but optional. We can safely ignore it.
91 fmap (SubBlock ∘ Unknown unknownID) getRemainingLazyByteString
93 instance Eq SubBlock where
94 (SubBlock a) == (SubBlock b)
97 instance Show SubBlock where
98 show (SubBlock a) = show a
100 -- | Dummy metadata to pad WavPack blocks.
105 deriving (Eq, Show, Typeable)
107 instance Metadata Dummy where
111 instance Binary Dummy where
112 put = putLazyByteString ∘ flip L.replicate 0x00 ∘ fromIntegral ∘ dumSize
113 get = fmap (Dummy ∘ fromIntegral) remaining
115 -- | Unknown but optional metadata found in the WavPack block.
119 , unkData ∷ L.ByteString
121 deriving (Eq, Show, Typeable)
123 instance Metadata Unknown where
125 metaSize = fromIntegral ∘ L.length ∘ unkData
127 instance Binary Unknown where
128 put = putLazyByteString ∘ unkData