1 ! Copyright (C) 2009 Joe Groff.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien.c-types alien.syntax audio combinators endian
4 combinators.short-circuit io io.binary io.encodings.binary
5 io.files io.streams.byte-array kernel locals math
6 sequences alien alien.data classes.struct accessors
7 audio.chunked-file audio.loader ;
10 CONSTANT: RIFF-MAGIC "RIFF"
11 CONSTANT: WAVE-MAGIC "WAVE"
12 CONSTANT: FMT-MAGIC "fmt "
13 CONSTANT: DATA-MAGIC "data"
15 STRUCT: riff-chunk-header
20 { header riff-chunk-header }
24 { header riff-chunk-header }
25 { audio-format uchar[2] }
26 { num-channels uchar[2] }
27 { sample-rate uchar[4] }
28 { byte-rate uchar[4] }
29 { block-align uchar[2] }
30 { bits-per-sample uchar[2] } ;
32 STRUCT: wav-data-chunk
33 { header riff-chunk-header }
36 : read-riff-chunk ( -- byte-array/f )
37 riff-chunk heap-size ensured-read* ;
39 :: read-wav-chunks ( -- fmt data )
41 [ { [ fmt data and not ] [ read-chunk ] } 0&& dup ]
43 { [ dup FMT-MAGIC wav-fmt-chunk check-chunk ] [ wav-fmt-chunk memory>struct fmt! ] }
44 { [ dup DATA-MAGIC wav-data-chunk check-chunk ] [ wav-data-chunk memory>struct data! ] }
47 fmt data 2dup and [ invalid-audio-file ] unless ;
49 : verify-wav ( chunk -- )
52 [ riff-chunk memory>struct format>> 4 memory>byte-array WAVE-MAGIC id= ]
54 [ invalid-audio-file ] unless ;
56 : (read-wav) ( -- audio )
59 [ num-channels>> 2 memory>byte-array le> ]
60 [ bits-per-sample>> 2 memory>byte-array le> ]
61 [ sample-rate>> 4 memory>byte-array le> ] tri
63 [ header>> size>> 4 memory>byte-array le> dup ]
64 [ body>> >c-ptr ] bi swap memory>byte-array
66 <audio> convert-data-endian ;
68 : read-wav ( filename -- audio )
71 read-riff-chunk verify-wav (read-wav)
75 "wav" [ read-wav ] register-audio-extension