1 ! Copyright (C) 2009 Joe Groff.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.c-types alien.data audio
4 audio.chunked-file audio.loader classes.struct combinators
5 combinators.short-circuit endian io.encodings.binary io.files
9 CONSTANT: RIFF-MAGIC "RIFF"
10 CONSTANT: WAVE-MAGIC "WAVE"
11 CONSTANT: FMT-MAGIC "fmt "
12 CONSTANT: DATA-MAGIC "data"
14 STRUCT: riff-chunk-header
19 { header riff-chunk-header }
23 { header riff-chunk-header }
24 { audio-format uchar[2] }
25 { num-channels uchar[2] }
26 { sample-rate uchar[4] }
27 { byte-rate uchar[4] }
28 { block-align uchar[2] }
29 { bits-per-sample uchar[2] } ;
31 STRUCT: wav-data-chunk
32 { header riff-chunk-header }
35 : read-riff-chunk ( -- byte-array/f )
36 riff-chunk heap-size ensured-read* ;
38 :: read-wav-chunks ( -- fmt data )
40 [ { [ fmt data and not ] [ read-chunk ] } 0&& ]
42 { [ dup FMT-MAGIC wav-fmt-chunk check-chunk ] [ wav-fmt-chunk memory>struct fmt! ] }
43 { [ dup DATA-MAGIC wav-data-chunk check-chunk ] [ wav-data-chunk memory>struct data! ] }
46 fmt data 2dup and [ invalid-audio-file ] unless ;
48 : verify-wav ( chunk -- )
51 [ riff-chunk memory>struct format>> 4 memory>byte-array WAVE-MAGIC id= ]
53 [ invalid-audio-file ] unless ;
55 : (read-wav) ( -- audio )
58 [ num-channels>> 2 memory>byte-array le> ]
59 [ bits-per-sample>> 2 memory>byte-array le> ]
60 [ sample-rate>> 4 memory>byte-array le> ] tri
62 [ header>> size>> 4 memory>byte-array le> dup ]
63 [ body>> >c-ptr ] bi swap memory>byte-array
65 <audio> convert-data-endian ;
67 : read-wav ( filename -- audio )
70 read-riff-chunk verify-wav (read-wav)
74 "wav" [ read-wav ] register-audio-extension