1 USING: alien.c-types alien.syntax audio combinators
2 combinators.short-circuit io io.binary io.encodings.binary
3 io.files io.streams.byte-array kernel locals math
4 sequences alien alien.data classes.struct accessors ;
7 CONSTANT: RIFF-MAGIC "RIFF"
8 CONSTANT: WAVE-MAGIC "WAVE"
9 CONSTANT: FMT-MAGIC "fmt "
10 CONSTANT: DATA-MAGIC "data"
12 STRUCT: riff-chunk-header
17 { header riff-chunk-header }
21 { header riff-chunk-header }
22 { audio-format uchar[2] }
23 { num-channels uchar[2] }
24 { sample-rate uchar[4] }
25 { byte-rate uchar[4] }
26 { block-align uchar[2] }
27 { bits-per-sample uchar[2] } ;
29 STRUCT: wav-data-chunk
30 { header riff-chunk-header }
33 ERROR: invalid-wav-file ;
35 : ensured-read ( count -- output/f )
36 [ read ] keep over length = [ drop f ] unless ;
37 : ensured-read* ( count -- output )
38 ensured-read [ invalid-wav-file ] unless* ;
40 : read-chunk ( -- byte-array/f )
41 4 ensured-read [ 4 ensured-read* dup le> ensured-read* 3append ] [ f ] if* ;
42 : read-riff-chunk ( -- byte-array/f )
43 riff-chunk heap-size ensured-read* ;
45 : id= ( chunk id -- ? )
46 [ 4 head ] dip sequence= ; inline
48 : check-chunk ( chunk id class -- ? )
49 heap-size [ id= ] [ [ length ] dip >= ] bi-curry* bi and ;
51 :: read-wav-chunks ( -- fmt data )
53 [ { [ fmt data and not ] [ read-chunk ] } 0&& dup ]
55 { [ dup FMT-MAGIC wav-fmt-chunk check-chunk ] [ wav-fmt-chunk memory>struct fmt! ] }
56 { [ dup DATA-MAGIC wav-data-chunk check-chunk ] [ wav-data-chunk memory>struct data! ] }
58 fmt data 2dup and [ invalid-wav-file ] unless ;
60 : verify-wav ( chunk -- )
63 [ riff-chunk memory>struct format>> 4 memory>byte-array WAVE-MAGIC id= ]
65 [ invalid-wav-file ] unless ;
67 : (read-wav) ( -- audio )
70 [ num-channels>> 2 memory>byte-array le> ]
71 [ bits-per-sample>> 2 memory>byte-array le> ]
72 [ sample-rate>> 4 memory>byte-array le> ] tri
74 [ header>> size>> 4 memory>byte-array le> dup ]
75 [ body>> >c-ptr ] bi swap memory>byte-array
78 : read-wav ( filename -- audio )
80 read-riff-chunk verify-wav (read-wav)