]> gitweb.factorcode.org Git - factor.git/commitdiff
make audio.wav endian-neutral
authorJoe Groff <arcata@gmail.com>
Tue, 19 Jan 2010 19:24:13 +0000 (11:24 -0800)
committerJoe Groff <arcata@gmail.com>
Tue, 19 Jan 2010 19:24:13 +0000 (11:24 -0800)
extra/audio/wav/wav.factor

index 89cd04ad60edff3ca6b916d3c5d79d73b2f17ac1..d1d432890d8f75999dab35a8c031e7ed3729015b 100644 (file)
@@ -1,4 +1,4 @@
-USING: alien.c-types alien.syntax audio combinators
+USING: alien.c-types alien.syntax audio combinators endian
 combinators.short-circuit io io.binary io.encodings.binary
 io.files io.streams.byte-array kernel locals math
 sequences alien alien.data classes.struct accessors ;
@@ -30,12 +30,12 @@ STRUCT: wav-data-chunk
     { header riff-chunk-header }
     { body uchar[0] } ;
 
-ERROR: invalid-wav-file ;
+ERROR: invalid-audio-file ;
 
 : ensured-read ( count -- output/f )
     [ read ] keep over length = [ drop f ] unless ;
 : ensured-read* ( count -- output )
-    ensured-read [ invalid-wav-file ] unless* ;
+    ensured-read [ invalid-audio-file ] unless* ;
 
 : read-chunk ( -- byte-array/f )
     4 ensured-read [ 4 ensured-read* dup le> ensured-read* 3append ] [ f ] if* ;
@@ -55,14 +55,23 @@ ERROR: invalid-wav-file ;
         { [ dup FMT-MAGIC  wav-fmt-chunk  check-chunk ] [ wav-fmt-chunk  memory>struct fmt!  ] }
         { [ dup DATA-MAGIC wav-data-chunk check-chunk ] [ wav-data-chunk memory>struct data! ] }
     } cond ] while drop
-    fmt data 2dup and [ invalid-wav-file ] unless ;
+    fmt data 2dup and [ invalid-audio-file ] unless ;
 
 : verify-wav ( chunk -- )
     {
         [ RIFF-MAGIC id= ]
         [ riff-chunk memory>struct format>> 4 memory>byte-array WAVE-MAGIC id= ]
     } 1&&
-    [ invalid-wav-file ] unless ;
+    [ invalid-audio-file ] unless ;
+
+: convert-data-endian ( audio -- audio )
+    little-endian [
+        dup sample-bits>> {
+            { 16 [ [ 2 seq>native-endianness ] change-data ] }
+            { 32 [ [ 4 seq>native-endianness ] change-data ] }
+            [ drop ]
+        } case
+    ] with-endianness ;
 
 : (read-wav) ( -- audio )
     read-wav-chunks
@@ -73,7 +82,9 @@ ERROR: invalid-wav-file ;
     ] [
         [ header>> size>> 4 memory>byte-array le> dup ]
         [ body>> >c-ptr ] bi swap memory>byte-array
-    ] bi* <audio> ;
+    ] bi*
+    <audio>
+    convert-data-endian ;
 
 : read-wav ( filename -- audio )
     binary [