shithub: sox

Download patch

ref: 6ae9ff7736c90e940c4f84be6877effa7cd451ca
parent: b029fc3c854e35152c3b0c6fd8dddd5e94ca0c9b
author: robs <robs>
date: Sat Mar 8 05:54:36 EST 2008

auto clean-up, fix, & additions

--- a/AUTHORS
+++ b/AUTHORS
@@ -24,7 +24,7 @@
                 Others: soxi, open input files via URL, file merging, play
                 multiple files with mixed format types, play with replay-gain,
                 building with cmake, much manual improvement and expansion,
-		improved displays with -S & -V including V.U. and clips,
+		improved displays with -S & -V including VU and clips,
                 various fixes, enhancements and clean-ups.
 
 Contributors:
--- a/ChangeLog
+++ b/ChangeLog
@@ -24,7 +24,7 @@
 
 File formats:
 
-  o New option --help-format shows info about supported formats.  (robs)
+  o New option --help-format shows info about supported format(s).  (robs)
   o New htk format.  (robs)
   o Fix [1864216] comments mangled when writing ogg-vorbis.  (robs)
   o Fix short noise at end of alsa playback.  (Morita Sho/Tim Munro/robs)
@@ -39,6 +39,8 @@
     encoding/decoding; display name of unsupported encoding.  (robs)
   o Can now write .amb (.wav variant) files [FR 1902232].  (robs)
   o Can now read 2,3(2.6),4 bit ADPCM .voc files [FR 1714991].  (robs)
+  o Fix auto-detect of hcom files.  (robs)
+  o Added auto-detect for caf, txw & sf files.  (robs)
 
 Effects:
 
@@ -60,6 +62,9 @@
     type is different to that of input file.  (robs)
   o SoX now treats (and displays) encoding size & signal precision
     separately.  (robs)
+  o Default audio devices (sox), and allow environment variables to
+    be used to override the default audio device driver (rec/play)
+    and default audio device (all).  (robs)
 
 Other bug fixes:
 
--- a/README
+++ b/README
@@ -76,7 +76,7 @@
   o De-emphasis filter
   o Move sound stage of CD audio to in front of you (for headphone
     use)
-  o Add an echo 
+  o Add an echo
   o Add a sequence of echos
   o Fade in and out
   o Apply a flanger effect
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -30,17 +30,17 @@
   echo            mixer           remix           stat
 )
 set(formats_srcs
-  8svx            cvsd            hcom            raw-fmt         u1-fmt
-  adpcm           cvsd-fmt        htk             s1-fmt          u2-fmt
-  adpcms          dat             ima-fmt         s2-fmt          u3-fmt
-  aifc-fmt        dvms-fmt        ima_rw          s3-fmt          u4-fmt
-  aiff            formats         la-fmt          s4-fmt          ul-fmt
-  aiff-fmt        g711            lpc10.c         sf              voc
-  al-fmt          g721            lu-fmt          skelform        vox
-  au              g723_24         maud            smp             vox-fmt
-  auto            g723_40         nulfile         sndrtool        wav
+  8svx            cvsd-fmt        htk             s1-fmt          u2-fmt
+  adpcm           dat             ima-fmt         s2-fmt          u3-fmt
+  adpcms          dvms-fmt        ima_rw          s3-fmt          u4-fmt
+  aifc-fmt        formats         la-fmt          s4-fmt          ul-fmt
+  aiff            g711            lpc10.c         sf              voc
+  aiff-fmt        g721            lu-fmt          skelform        vox
+  al-fmt          g723_24         maud            smp             vox-fmt
+  au              g723_40         nulfile         sndrtool        wav
   avr             g72x            prc             sphere          wve
   cdr             gsm.c           raw             tx16w           xa
+  cvsd            hcom            raw-fmt         u1-fmt
 )
 add_library(lib${PROJECT_NAME}
   ${effects_srcs}         misc                    util
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -31,7 +31,7 @@
 AM_LDFLAGS = $(LIBLTDL)
 
 # Format modules; listed first so optional ones can be added later
-pkglib_LTLIBRARIES = libsox_fmt_auto.la libsox_fmt_raw.la libsox_fmt_s1.la \
+pkglib_LTLIBRARIES = libsox_fmt_raw.la libsox_fmt_s1.la \
 	  libsox_fmt_s2.la libsox_fmt_s3.la libsox_fmt_s4.la libsox_fmt_u1.la \
 	  libsox_fmt_u2.la libsox_fmt_u3.la libsox_fmt_u4.la		\
 	  libsox_fmt_al.la libsox_fmt_la.la libsox_fmt_ul.la		\
@@ -46,10 +46,6 @@
 	  libsox_fmt_wve.la libsox_fmt_xa.la libsox_fmt_nul.la \
 	  libsox_fmt_htk.la
 
-# File format detection
-libsox_fmt_auto_la_SOURCES = auto.c
-libsox_fmt_auto_la_LIBADD = libsox.la
-
 # File formats
 libsox_fmt_raw_la_SOURCES = raw-fmt.c
 libsox_fmt_raw_la_LIBADD = libsox.la
@@ -219,7 +215,7 @@
 
 if HAVE_LIBLTDL
 else
-  libsox_la_SOURCES += auto.c raw-fmt.c s1-fmt.c s2-fmt.c s3-fmt.c \
+  libsox_la_SOURCES += raw-fmt.c s1-fmt.c s2-fmt.c s3-fmt.c \
     s4-fmt.c u1-fmt.c u2-fmt.c u3-fmt.c u4-fmt.c al-fmt.c la-fmt.c ul-fmt.c \
     lu-fmt.c 8svx.c aiff-fmt.c aifc-fmt.c au.c avr.c cdr.c cvsd-fmt.c \
     dvms-fmt.c dat.c gsm.c hcom.c htk.c lpc10.c maud.c prc.c sf.c sfircam.h smp.c \
--- a/src/auto.c
+++ /dev/null
@@ -1,173 +1,0 @@
-/*
- * May 19, 1992
- * Copyright 1992 Guido van Rossum And Sundry Contributors
- * This source code is freely redistributable and may be used for
- * any purpose.  This copyright notice must be maintained. 
- * Guido van Rossum And Sundry Contributors are not responsible for 
- * the consequences of using this software.
- */
-
-/*
- * A meta-handler that recognizes most file types by looking in the
- * first part of the file.  The file must be seekable!
- * (IRCAM sound files are not recognized -- these don't seem to be
- * used any more -- but this is just laziness on my part.) 
- */
-
-#include "sox_i.h"
-#include <string.h>
-
-static int sox_autostartread(sox_format_t * ft)
-{
-    char const * type = NULL;
-    char header[256];
-    int rc, loop;
-
-    /* Attempt to auto-detect filetype using magic values.  Abort loop
-     * and use file extension if any errors are detected.
-     */
-    if (ft->seekable)
-    {
-        /* Most files only have 4-byte magic headers at first of
-         * file.  So we start checking for those filetypes first.
-         */
-        memset(header,0,4);
-        if (sox_readbuf(ft, header, 4) == 4)
-        {
-            /* Look for .snd or dns. header of AU files */
-            if ((strncmp(header, ".snd", 4) == 0) ||
-                (strncmp(header, "dns.", 4) == 0) ||
-                ((header[0] == '\0') && 
-                 (strncmp(header+1, "ds.", 3) == 0)) ||
-                ((strncmp(header, "sd.", 3) == 0) && 
-                 (header[3] == '\0')))
-                type = "au";
-            else if (strncmp(header, "FORM", 4) == 0) 
-            {
-                /* Need to read more data to see what type of FORM file */
-                if (sox_readbuf(ft, header, 8) == 8)
-                {
-                    if (strncmp(header + 4, "AIFF", 4) == 0)
-                        type = "aiff";
-                    else if (strncmp(header + 4, "AIFC", 4) == 0)
-                        type = "aiff";
-                    else if (strncmp(header + 4, "8SVX", 4) == 0)
-                        type = "8svx";
-                    else if (strncmp(header + 4, "MAUD", 4) == 0)
-                        type = "maud";
-                }
-            }
-            else if (strncmp(header, "RIFF", 4) == 0 ||
-                     strncmp(header, "RIFX", 4) == 0) {
-                if (sox_readbuf(ft, header, 8) == 8)
-                    if (strncmp(header + 4, "WAVE", 4) == 0)
-                        type = "wav";
-            }
-            else if (strncmp(header, "Crea", 4) == 0) 
-            {
-                if (sox_readbuf(ft, header, 15) == 15)
-                    if (strncmp(header, "tive Voice File", 15) == 0) 
-                        type = "voc";
-            }
-            else if (strncmp(header, "SOUN", 4) == 0)
-            {
-                /* Check for SOUND magic header */
-                if (sox_readbuf(ft, header, 1) == 1 && *header == 'D')
-                {
-                    /* Once we've found SOUND see if its smp or sndt */
-                    if (sox_readbuf(ft, header, 12) == 12)
-                    {
-                        if (strncmp(header, " SAMPLE DATA", 12) == 0)
-                            type = "smp";
-                        else
-                            type = "sndt";
-                    }
-                    else
-                        type = "sndt";
-                }
-            }
-            else if (strncmp(header, "2BIT", 4) == 0) 
-                type = "avr";
-            else if (strncmp(header, "NIST", 4) == 0) 
-            {
-                if (sox_readbuf(ft, header, 3) == 3)
-                    if (strncmp(header, "_1A", 3) == 0) 
-                        type = "sph";
-            }
-            else if (strncmp(header, "ALaw", 4) == 0)
-            {
-                if (sox_readbuf(ft, header, 11) == 11)
-                    if (strncmp(header, "SoundFile**", 11) == 0)
-                        type = "wve";
-            }
-            else if (strncmp(header, "Ogg", 3) == 0)
-                type = "ogg";
-            else if (strncmp(header, "fLaC", 4) == 0)
-                type = "flac";
-            else if ((memcmp(header, "XAI\0", 4) == 0) ||
-                     (memcmp(header, "XAJ\0", 4) == 0) ||
-                     (memcmp(header, "XA\0\0", 4) == 0))
-                type = "xa";
-            else if (strncmp(header, "#!AM", 4) == 0) {
-              rc = sox_readbuf(ft, header, 5);
-              if (rc >= 2 && strncmp(header, "R\n", 2) == 0)
-                type = "amr-nb";
-              else if (rc >= 5 && strncmp(header, "R-WB\n", 5) == 0)
-                type = "amr-wb";
-            }
-        } /* read 4-byte header */
-
-        /* If we didn't find type yet then start looking for file
-         * formats that the magic header is deeper in the file.
-         */
-        if (type == NULL)
-        {
-            for (loop = 0; loop < 60; loop++)
-                if (sox_readbuf(ft, header, 1) != 1)
-                    break;
-            if (sox_readbuf(ft, header, 4) == 4 && 
-                strncmp(header, "FSSD", 4) == 0)
-            {
-                for (loop = 0; loop < 62; loop++)
-                    if (sox_readbuf(ft, header, 1) != 1)
-                        break;
-                if (sox_readbuf(ft, header, 4) == 0 && 
-                    strncmp(header, "HCOM", 4) == 0)
-                    type = "hcom";
-            }
-        }
-
-        sox_rewind(ft);
-
-        if (type == NULL) {
-          if (prc_checkheader(ft, header))
-            type = "prc";
-          sox_rewind(ft);
-        }        
-    } /* if (seekable) */
-
-    if (type == NULL)
-      type = find_file_extension(ft->filename);
-
-    free(ft->filetype);
-    ft->filetype = xstrdup(type);
-    ft->mode = 'r';
-    rc = sox_gettype(ft, sox_true); /* Change to the new format */
-    if (rc != SOX_SUCCESS)
-      return (rc);
-
-    sox_debug("Detected file format type: %s", type);
-    set_endianness_if_not_already_set(ft);
-    return ft->handler.startread? (*ft->handler.startread)(ft) : SOX_SUCCESS;
-}
-
-SOX_FORMAT_HANDLER(auto)
-{
-  static const char *autonames[] = {"magic", NULL};
-  static sox_format_handler_t sox_auto_format = {
-    NULL,
-    autonames, SOX_FILE_DEVICE | SOX_FILE_PHONY,
-    sox_autostartread, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
-  };
-  return &sox_auto_format;
-}
--- a/src/formats.c
+++ b/src/formats.c
@@ -34,7 +34,7 @@
 {
   sox_size_t f, n;
 
-  for (f = 0; f < sox_formats; ++f) {
+  if (name) for (f = 0; f < sox_formats; ++f) {
     sox_format_handler_t const * fh = sox_format_fns[f].fn();
 
     if (!(no_dev && (fh->flags & SOX_FILE_DEVICE)))
--- a/src/formats.h
+++ b/src/formats.h
@@ -4,7 +4,6 @@
   FORMAT(aiff)
   FORMAT(al)
   FORMAT(au)
-  FORMAT(auto)
   FORMAT(avr)
   FORMAT(cdr)
   FORMAT(cvsd)
--- a/src/sox_i.h
+++ b/src/sox_i.h
@@ -147,7 +147,6 @@
 int sox_reads(sox_format_t * ft, char *c, sox_size_t len);
 int sox_writes(sox_format_t * ft, char const * c);
 void set_signal_defaults(sox_signalinfo_t * signal);
-void set_endianness_if_not_already_set(sox_format_t * ft);
 
 sox_size_t sox_read_b_buf(sox_format_t * ft, uint8_t *buf, sox_size_t len);
 sox_size_t sox_read_w_buf(sox_format_t * ft, uint16_t *buf, sox_size_t len);
--- a/src/soxio.c
+++ b/src/soxio.c
@@ -1,3 +1,21 @@
+/*
+ * libSoX IO routines       (c) 2005-8 Chris Bagwell and SoX contributors
+ *
+ * This library is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library.  If not, write to the Free Software Foundation,
+ * Fifth Floor, 51 Franklin Street, Boston, MA 02111-1301, USA.
+ */
+
 #include "sox_i.h"
 
 #include <assert.h>
@@ -84,6 +102,21 @@
 }
 
 /*
+ * Cleanup things.
+ */
+void sox_format_quit(void)
+{
+#ifdef HAVE_LIBLTDL
+  {
+    int ret;
+    if (plugins_initted && (ret = lt_dlexit()) != 0) {
+      sox_fail("lt_dlexit failed with %d error(s): %s", ret, lt_dlerror());
+    }
+  }
+#endif
+}
+
+/*
  * Check that we have a known format suffix string.
  */
 int sox_gettype(sox_format_t * ft, sox_bool is_file_extension)
@@ -100,10 +133,6 @@
     return SOX_EFMT;
   }
   ft->handler = *handler;
-  if (ft->mode == 'r' && !ft->handler.startread && !ft->handler.read) {
-    sox_fail_errno(ft, SOX_EFMT, "file type `%s' isn't readable", ft->filetype);
-    return SOX_EFMT;
-  }
   if (ft->mode == 'w' && !ft->handler.startwrite && !ft->handler.write) {
     sox_fail_errno(ft, SOX_EFMT, "file type `%s' isn't writable", ft->filetype);
     return SOX_EFMT;
@@ -111,21 +140,6 @@
   return SOX_SUCCESS;
 }
 
-/*
- * Cleanup things.
- */
-void sox_format_quit(void)
-{
-#ifdef HAVE_LIBLTDL
-  {
-    int ret;
-    if (plugins_initted && (ret = lt_dlexit()) != 0) {
-      sox_fail("lt_dlexit failed with %d error(s): %s", ret, lt_dlerror());
-    }
-  }
-#endif
-}
-
 void set_signal_defaults(sox_signalinfo_t * signal)
 {
   if (!signal->rate    ) signal->rate     = SOX_DEFAULT_RATE;
@@ -133,7 +147,7 @@
   if (!signal->channels) signal->channels = SOX_DEFAULT_CHANNELS;
 }
 
-void set_endianness_if_not_already_set(sox_format_t * ft)
+static void set_endianness_if_not_already_set(sox_format_t * ft)
 {
   if (ft->encoding.reverse_bytes == SOX_OPTION_DEFAULT) {
     if (ft->handler.flags & SOX_FILE_ENDIAN)
@@ -162,11 +176,10 @@
 
 static int is_seekable(sox_format_t * ft)
 {
-        struct stat st;
+  struct stat st;
 
-        fstat(fileno(ft->fp), &st);
-
-        return ((st.st_mode & S_IFMT) == S_IFREG);
+  fstat(fileno(ft->fp), &st);
+  return ((st.st_mode & S_IFMT) == S_IFREG);
 }
 
 /* check that all settings have been given */
@@ -185,6 +198,44 @@
   return SOX_SUCCESS;
 }
 
+static char const * detect_magic(sox_format_t * ft)
+{
+  char data[256];
+  size_t len = sox_readbuf(ft, data, sizeof(data));
+  #define MAGIC(type, p2, l2, d2, p1, l1, d1) if (len >= p1 + l1 && \
+      !memcmp(data + p1, d1, l1) && !memcmp(data + p2, d2, l2)) return #type;
+  MAGIC(voc   , 0, 0, ""     , 0, 20, "Creative Voice File\x1a")
+  MAGIC(smp   , 0, 0, ""     , 0, 17, "SOUND SAMPLE DATA")
+  MAGIC(wve   , 0, 0, ""     , 0, 15, "ALawSoundFile**")
+  MAGIC(amr-wb, 0, 0, ""     , 0,  9, "#!AMR-WB\n")
+  MAGIC(prc   , 0, 0, ""     , 0,  8, prc_header)
+  MAGIC(sph   , 0, 0, ""     , 0,  7, "NIST_1A")
+  MAGIC(amr-nb, 0, 0, ""     , 0,  6, "#!AMR\n")
+  MAGIC(txw   , 0, 0, ""     , 0,  6, "LM8953")
+  MAGIC(sndt  , 0, 0, ""     , 0,  5, "SOUND")
+  MAGIC(vorbis, 0, 4, "OggS" , 29, 6, "vorbis")
+  MAGIC(speex , 0, 4, "OggS" , 28, 6, "Speex")
+  MAGIC(hcom  ,65, 4, "FSSD" , 128,4, "HCOM")
+  MAGIC(wav   , 0, 4, "RIFF" , 8,  4, "WAVE")
+  MAGIC(wav   , 0, 4, "RIFX" , 8,  4, "WAVE")
+  MAGIC(aiff  , 0, 4, "FORM" , 8,  4, "AIFF")
+  MAGIC(aifc  , 0, 4, "FORM" , 8,  4, "AIFC")
+  MAGIC(8svx  , 0, 4, "FORM" , 8,  4, "8SVX")
+  MAGIC(maud  , 0, 4, "FORM" , 8,  4, "MAUD")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XA\0\0")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAI\0")
+  MAGIC(xa    , 0, 0, ""     , 0,  4, "XAJ\0")
+  MAGIC(au    , 0, 0, ""     , 0,  4, "\0ds.")
+  MAGIC(au    , 0, 0, ""     , 0,  4, ".snd")
+  MAGIC(flac  , 0, 0, ""     , 0,  4, "fLaC")
+  MAGIC(avr   , 0, 0, ""     , 0,  4, "2BIT")
+  MAGIC(caf   , 0, 0, ""     , 0,  4, "caff")
+  MAGIC(paf   , 0, 0, ""     , 0,  4, " paf")
+  MAGIC(sf    , 3, 1, ""     , 0,  2, "\144\243")
+  #undef MAGIC
+  return NULL;
+}
+
 sox_format_t * sox_open_read(
     char               const * path,
     sox_signalinfo_t   const * signal,
@@ -191,86 +242,99 @@
     sox_encodinginfo_t const * encoding,
     char               const * filetype)
 {
-    sox_format_t * ft = xcalloc(sizeof(*ft), 1);
+  sox_format_t * ft = xcalloc(1, sizeof(*ft));
+  sox_format_handler_t const * handler;
 
-    ft->filename = xstrdup(path);
-
-    /* Let auto type do the work if user is not overriding. */
-    if (!filetype)
-        ft->filetype = xstrdup("magic");
-    else
-        ft->filetype = xstrdup(filetype);
-
-    ft->mode = 'r';
-    if (sox_gettype(ft, sox_false) != SOX_SUCCESS) {
-      sox_fail("Can't open input file `%s': %s", ft->filename, ft->sox_errstr);
-      goto input_error;
+  if (filetype) {
+    if (!(handler = sox_find_format(filetype, sox_false))) {
+      sox_fail("no handler for given file type `%s'", filetype);
+      goto error;
     }
-    if (signal)
-      ft->signal = *signal;
-    if (encoding)
-      ft->encoding = *encoding;
-    else sox_init_encodinginfo(&ft->encoding);
+    ft->handler = *handler;
+  }
 
-    if (!(ft->handler.flags & SOX_FILE_NOSTDIO))
-    {
-        /* Open file handler based on input name.  Used stdin file handler
-         * if the filename is "-"
-         */
-        if (!strcmp(ft->filename, "-")) {
-          if (sox_globals.stdin_in_use_by) {
-            sox_fail("'-' (stdin) already in use by '%s'", sox_globals.stdin_in_use_by);
-            goto input_error;
-          }
-          sox_globals.stdin_in_use_by = "audio input";
-          SET_BINARY_MODE(stdin);
-          ft->fp = stdin;
-        }
-        else if ((ft->fp = xfopen(ft->filename, "rb")) == NULL)
-        {
-            sox_fail("Can't open input file `%s': %s", ft->filename,
-                    strerror(errno));
-            goto input_error;
-        }
-
-        /* See if this file is seekable or not */
-        ft->seekable = is_seekable(ft);
+  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
+    if (!strcmp(path, "-")) { /* Use stdin if the filename is "-" */
+      if (sox_globals.stdin_in_use_by) {
+        sox_fail("`-' (stdin) already in use by `%s'", sox_globals.stdin_in_use_by);
+        goto error;
+      }
+      sox_globals.stdin_in_use_by = "audio input";
+      SET_BINARY_MODE(stdin);
+      ft->fp = stdin;
     }
+    else if ((ft->fp = xfopen(path, "rb")) == NULL) {
+      sox_fail("can't open input file `%s': %s", path, strerror(errno));
+      goto error;
+    }
+    ft->seekable = is_seekable(ft);
+  }
 
-    if (filetype)
-      set_endianness_if_not_already_set(ft);
-
-    /* Read and write starters can change their formats. */
-    if (ft->handler.startread && (*ft->handler.startread)(ft) != SOX_SUCCESS)
-    {
-        sox_fail("Can't open input file `%s': %s", ft->filename, ft->sox_errstr);
-        goto input_error;
+  if (!filetype) {
+    if (ft->seekable) {
+      filetype = detect_magic(ft);
+      sox_rewind(ft);
     }
+    if (filetype) {
+      sox_report("detected file format type `%s'", filetype);
+      if (!(handler = sox_find_format(filetype, sox_false))) {
+        sox_fail("no handler for detected file type `%s'", filetype);
+        goto error;
+      }
+    }
+    else {
+      if (!(filetype = find_file_extension(path))) {
+        sox_fail("can't determine type of `%s'", path);
+        goto error;
+      }
+      if (!(handler = sox_find_format(filetype, sox_true))) {
+        sox_fail("no handler for file extension `%s'", filetype);
+        goto error;
+      }
+    }
+    ft->handler = *handler;
+  }
+  if (!ft->handler.startread && !ft->handler.read) {
+    sox_fail("file type `%s' isn't readable", filetype);
+    goto error;
+  }
+  
+  ft->mode = 'r';
+  
+  if (signal)
+    ft->signal = *signal;
+  
+  if (encoding)
+    ft->encoding = *encoding;
+  else sox_init_encodinginfo(&ft->encoding);
+  set_endianness_if_not_already_set(ft);
 
-    if (!ft->signal.precision)
-      ft->signal.precision = sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample);
+  ft->filetype = xstrdup(filetype);
+  ft->filename = xstrdup(path);
 
-    /* Go ahead and assume 1 channel audio if nothing is detected.
-     * This is because libsox usually doesn't set this for mono file
-     * formats (for historical reasons).
-     */
-    if (!(ft->handler.flags & SOX_FILE_PHONY) && !ft->signal.channels)
-      ft->signal.channels = 1;
+  /* Read and write starters can change their formats. */
+  if (ft->handler.startread && (*ft->handler.startread)(ft) != SOX_SUCCESS) {
+    sox_fail("can't open input file `%s': %s", ft->filename, ft->sox_errstr);
+    goto error;
+  }
 
-    if (sox_checkformat(ft) )
-    {
-        sox_fail("bad input format for file %s: %s", ft->filename,
-                ft->sox_errstr);
-        goto input_error;
-    }
+  /* Fill in some defaults: */
+  if (!ft->signal.precision)
+    ft->signal.precision = sox_precision(ft->encoding.encoding, ft->encoding.bits_per_sample);
+  if (!(ft->handler.flags & SOX_FILE_PHONY) && !ft->signal.channels)
+    ft->signal.channels = 1;
+
+  if (sox_checkformat(ft) == SOX_SUCCESS)
     return ft;
+  sox_fail("bad input format for file `%s': %s", ft->filename, ft->sox_errstr);
 
-input_error:
-
-    free(ft->filename);
-    free(ft->filetype);
-    free(ft);
-    return NULL;
+error:
+  if (ft->fp && ft->fp != stdin)
+    fclose(ft->fp);
+  free(ft->filename);
+  free(ft->filetype);
+  free(ft);
+  return NULL;
 }
 
 static void set_output_format(sox_format_t * ft)
@@ -485,7 +549,7 @@
   ft->mode = 'w';
   if (sox_gettype(ft, no_filetype_given) != SOX_SUCCESS) {
     sox_fail("Can't open output file `%s': %s", ft->filename, ft->sox_errstr);
-    goto output_error;
+    goto error;
   }
   ft->signal = *signal;
   if (encoding)
@@ -492,44 +556,36 @@
     ft->encoding = *encoding;
   else sox_init_encodinginfo(&ft->encoding);
 
-  if (!(ft->handler.flags & SOX_FILE_NOSTDIO))
-  {
-      /* Open file handler based on output name.  Used stdout file handler
-       * if the filename is "-"
-       */
-      if (!strcmp(ft->filename, "-")) {
-        if (sox_globals.stdout_in_use_by) {
-          sox_fail("'-' (stdout) already in use by '%s'", sox_globals.stdout_in_use_by);
-          goto output_error;
-        }
-        sox_globals.stdout_in_use_by = "audio output";
-          SET_BINARY_MODE(stdout);
-          ft->fp = stdout;
+  if (!(ft->handler.flags & SOX_FILE_NOSTDIO)) {
+    if (!strcmp(ft->filename, "-")) { /* Use stdout if the filename is "-" */
+      if (sox_globals.stdout_in_use_by) {
+        sox_fail("`-' (stdout) already in use by `%s'", sox_globals.stdout_in_use_by);
+        goto error;
       }
-      else {
-        struct stat st;
-        if (!stat(ft->filename, &st) && (st.st_mode & S_IFMT) == S_IFREG &&
-            (overwrite_permitted && !overwrite_permitted(ft->filename))) {
-          sox_fail("Permission to overwrite '%s' denied", ft->filename);
-          goto output_error;
-        }
-        if ((ft->fp = fopen(ft->filename, "wb")) == NULL) {
-          sox_fail("Can't open output file `%s': %s", ft->filename,
-                  strerror(errno));
-          goto output_error;
-        }
+      sox_globals.stdout_in_use_by = "audio output";
+      SET_BINARY_MODE(stdout);
+      ft->fp = stdout;
+    }
+    else {
+      struct stat st;
+      if (!stat(ft->filename, &st) && (st.st_mode & S_IFMT) == S_IFREG &&
+          (overwrite_permitted && !overwrite_permitted(ft->filename))) {
+        sox_fail("Permission to overwrite '%s' denied", ft->filename);
+        goto error;
       }
-
-      /* stdout tends to be line-buffered.  Override this */
-      /* to be Full Buffering. */
-      if (setvbuf (ft->fp, NULL, _IOFBF, sizeof(char) * sox_globals.bufsiz))
-      {
-          sox_fail("Can't set write buffer");
-          goto output_error;
+      if ((ft->fp = fopen(ft->filename, "wb")) == NULL) {
+        sox_fail("can't open output file `%s': %s", ft->filename, strerror(errno));
+        goto error;
       }
+    }
 
-      /* See if this file is seekable or not */
-      ft->seekable = is_seekable(ft);
+    /* stdout tends to be line-buffered.  Override this */
+    /* to be Full Buffering. */
+    if (setvbuf (ft->fp, NULL, _IOFBF, sizeof(char) * sox_globals.bufsiz)) {
+      sox_fail("Can't set write buffer");
+      goto error;
+    }
+    ft->seekable = is_seekable(ft);
   }
 
   ft->comments = copy_comments(comments);
@@ -557,7 +613,7 @@
   /* Read and write starters can change their formats. */
   if (ft->handler.startwrite && (ft->handler.startwrite)(ft) != SOX_SUCCESS){
     sox_fail("can't open output file `%s': %s", ft->filename, ft->sox_errstr);
-    goto output_error;
+    goto error;
   }
 
   if (sox_checkformat(ft) == SOX_SUCCESS)
@@ -564,7 +620,9 @@
     return ft;
   sox_fail("bad format for output file `%s': %s", ft->filename, ft->sox_errstr);
 
-output_error:
+error:
+  if (ft->fp && ft->fp != stdout)
+    fclose(ft->fp);
   free(ft->filename);
   free(ft->filetype);
   free(ft);