]> gitweb.factorcode.org Git - factor.git/blob - extra/audio/aiff/aiff.factor
factor: trim using lists
[factor.git] / extra / audio / aiff / aiff.factor
1 ! Copyright (C) 2009 Joe Groff.
2 ! See http://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
6 kernel math sequences ;
7 IN: audio.aiff
8
9 CONSTANT: FORM-MAGIC "FORM"
10 CONSTANT: AIFF-MAGIC "AIFF"
11 CONSTANT: COMM-MAGIC "COMM"
12 CONSTANT: SSND-MAGIC "SSND"
13
14 STRUCT: aiff-chunk-header
15     { id char[4] }
16     { size char[4] } ;
17
18 STRUCT: form-chunk
19     { header aiff-chunk-header }
20     { form-type char[4] } ;
21
22 STRUCT: common-chunk
23     { header aiff-chunk-header }
24     { num-channels uchar[2] }
25     { num-sample-frames uchar[4] }
26     { sample-size uchar[2] }
27     { sample-rate uchar[10] } ;
28
29 STRUCT: sound-data-chunk
30     { header aiff-chunk-header }
31     { offset uchar[4] }
32     { block-size uchar[4] }
33     { waveform-data uchar[0] } ;
34
35 ! cheesy long-double>integer converter that assumes the long double is a positive integer
36 : sample-rate>integer ( byte[10] -- sample-rate )
37     2 cut-slice [ be> ] bi@ swap 16383 - 63 - shift ;
38
39 : read-form-chunk ( -- byte-array/f )
40     form-chunk heap-size ensured-read* ;
41
42 : verify-aiff ( chunk -- )
43     {
44         [ FORM-MAGIC id= ]
45         [ form-chunk memory>struct form-type>> 4 memory>byte-array AIFF-MAGIC id= ]
46     } 1&&
47     [ invalid-audio-file ] unless ;
48
49 :: read-aiff-chunks ( -- comm ssnd )
50     f :> comm! f :> ssnd!
51     [ { [ comm ssnd and not ] [ read-chunk ] } 0&& dup ]
52     [ {
53         {
54             [ dup COMM-MAGIC common-chunk check-chunk ]
55             [ common-chunk memory>struct comm! ]
56         }
57         {
58             [ dup SSND-MAGIC sound-data-chunk check-chunk ]
59             [ sound-data-chunk memory>struct ssnd! ]
60         }
61         [ drop ]
62     } cond ] while drop
63     comm ssnd 2dup and [ invalid-audio-file ] unless ;
64
65 : (read-aiff) ( -- audio )
66     read-aiff-chunks
67     [
68         [ num-channels>>    2 memory>byte-array be> ]
69         [ sample-size>>     2 memory>byte-array be> ]
70         [ sample-rate>>     sample-rate>integer ] tri
71     ] [
72         [ header>> size>> 4 memory>byte-array be> 8 - dup ]
73         [ waveform-data>> >c-ptr ] bi swap memory>byte-array
74     ] bi*
75     <audio> convert-data-endian ;
76
77 : read-aiff ( filename -- audio )
78     big-endian [
79         binary [
80             read-form-chunk verify-aiff (read-aiff)
81         ] with-file-reader
82     ] with-endianness ;
83
84 "aif"  [ read-aiff ] register-audio-extension
85 "aiff" [ read-aiff ] register-audio-extension