1d09d18
diff --git a/src/ao.c b/src/ao.c
1d09d18
index 4791d4e..3d6431d 100644
1d09d18
--- a/src/ao.c
1d09d18
+++ b/src/ao.c
1d09d18
@@ -34,9 +34,21 @@ typedef struct {
1d09d18
 static int startwrite(sox_format_t * ft)
1d09d18
 {
1d09d18
   priv_t * ao = (priv_t *)ft->priv;
1d09d18
+  unsigned bytes_per_sample = (ft->encoding.bits_per_sample + 7) >> 3;
1d09d18
 
1d09d18
-  ao->buf_size = sox_globals.bufsiz - (sox_globals.bufsiz % (ft->encoding.bits_per_sample >> 3));
1d09d18
-  ao->buf_size *= (ft->encoding.bits_per_sample >> 3);
1d09d18
+  if (bytes_per_sample == 0)
1d09d18
+  {
1d09d18
+      lsx_fail("startwrite [ao driver]: Corrupted encoding data (bits per sample should not be zero)");
1d09d18
+      return SOX_EOF;
1d09d18
+  }
1d09d18
+
1d09d18
+  /* Since sox_sw_write_buf works with 16-bit samples, ensure there is an enough room */
1d09d18
+  if (bytes_per_sample < 2)
1d09d18
+    bytes_per_sample = 2;
1d09d18
+  /* Align the buffer size to the boundary divisible by bytes_per_sample */
1d09d18
+  ao->buf_size = sox_globals.bufsiz - (sox_globals.bufsiz % bytes_per_sample);
1d09d18
+  /* - add back possibly truncated bytes */
1d09d18
+  ao->buf_size += bytes_per_sample;
1d09d18
   ao->buf = lsx_malloc(ao->buf_size);
1d09d18
 
1d09d18
   if (!ao->buf)
1d09d18
@@ -90,12 +102,17 @@ static void sox_sw_write_buf(char *buf1, sox_sample_t const * buf2, size_t len,
1d09d18
 static size_t write_samples(sox_format_t *ft, const sox_sample_t *buf, size_t len)
1d09d18
 {
1d09d18
   priv_t * ao = (priv_t *)ft->priv;
1d09d18
+  /* This will be always > 0 in the case the format handler is properly used */
1d09d18
+  unsigned bytes_per_sample = (ft->encoding.bits_per_sample + 7) >> 3;
1d09d18
   uint_32 aobuf_size;
1d09d18
 
1d09d18
-  if (len > ao->buf_size / (ft->encoding.bits_per_sample >> 3))
1d09d18
-      len = ao->buf_size / (ft->encoding.bits_per_sample >> 3);
1d09d18
+  /* Normalize the number of samples */
1d09d18
+  if (bytes_per_sample < 2)
1d09d18
+      bytes_per_sample = 2;
1d09d18
+  if (len > ao->buf_size / bytes_per_sample)
1d09d18
+      len = ao->buf_size / bytes_per_sample;
1d09d18
 
1d09d18
-  aobuf_size = (ft->encoding.bits_per_sample >> 3) * len;
1d09d18
+  aobuf_size = bytes_per_sample * len;
1d09d18
 
1d09d18
   sox_sw_write_buf(ao->buf, buf, len, ft->encoding.reverse_bytes,
1d09d18
                    &(ft->clips));