]> gitweb.factorcode.org Git - factor.git/blob - extra/audio/wav/wav.factor
0a5c242db8c36b31939b51998671caf60e4df0a6
[factor.git] / extra / audio / wav / wav.factor
1 ! (c)2009 Joe Groff bsd license
2 USING: alien.c-types alien.syntax audio combinators endian
3 combinators.short-circuit io io.binary io.encodings.binary
4 io.files io.streams.byte-array kernel locals math
5 sequences alien alien.data classes.struct accessors
6 audio.chunked-file audio.loader ;
7 IN: audio.wav
8
9 CONSTANT: RIFF-MAGIC "RIFF"
10 CONSTANT: WAVE-MAGIC "WAVE"
11 CONSTANT: FMT-MAGIC  "fmt "
12 CONSTANT: DATA-MAGIC "data"
13
14 STRUCT: riff-chunk-header
15     { id char[4] }
16     { size char[4] } ;
17
18 STRUCT: riff-chunk
19     { header riff-chunk-header }
20     { format char[4] } ;
21
22 STRUCT: wav-fmt-chunk
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] } ;
30
31 STRUCT: wav-data-chunk
32     { header riff-chunk-header }
33     { body uchar[0] } ;
34
35 : read-riff-chunk ( -- byte-array/f )
36     riff-chunk heap-size ensured-read* ;
37
38 :: read-wav-chunks ( -- fmt data )
39     f :> fmt! f :> data!
40     [ { [ fmt data and not ] [ read-chunk ] } 0&& dup ]
41     [ {
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! ] }
44         [ drop ]
45     } cond ] while drop
46     fmt data 2dup and [ invalid-audio-file ] unless ;
47
48 : verify-wav ( chunk -- )
49     {
50         [ RIFF-MAGIC id= ]
51         [ riff-chunk memory>struct format>> 4 memory>byte-array WAVE-MAGIC id= ]
52     } 1&&
53     [ invalid-audio-file ] unless ;
54
55 : (read-wav) ( -- audio )
56     read-wav-chunks
57     [
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
61     ] [
62         [ header>> size>> 4 memory>byte-array le> dup ]
63         [ body>> >c-ptr ] bi swap memory>byte-array
64     ] bi*
65     <audio> convert-data-endian ;
66
67 : read-wav ( filename -- audio )
68     little-endian [
69         binary [
70             read-riff-chunk verify-wav (read-wav)
71         ] with-file-reader
72     ] with-endianness ;
73
74 "wav" [ read-wav ] register-audio-extension