Fix shortened floating point WAV file write

Also fix minor robustness issue in sf_open_write in case
the target WAV file is opened in a protected directory.

Change-Id: I4f9a0e2ba92b9e851bd034e40169513e7e08a92b
diff --git a/audio_utils/tinysndfile.c b/audio_utils/tinysndfile.c
index 15b3a81..0d9a711 100644
--- a/audio_utils/tinysndfile.c
+++ b/audio_utils/tinysndfile.c
@@ -251,6 +251,10 @@
         return NULL;
     }
     FILE *stream = fopen(path, "w+b");
+    if (stream == NULL) {
+        fprintf(stderr, "fopen %s failed errno %d\n", path, errno);
+        return NULL;
+    }
     unsigned char wav[58];
     memset(wav, 0, sizeof(wav));
     memcpy(wav, "RIFF", 4);
@@ -508,7 +512,8 @@
         break;
     case SF_FORMAT_FLOAT:
         handle->temp = realloc(handle->temp, desiredBytes);
-        memcpy_to_float_from_i16((float *) handle->temp, ptr, desiredFrames);
+        memcpy_to_float_from_i16((float *) handle->temp, ptr,
+                desiredFrames * handle->info.channels);
         actualBytes = fwrite(handle->temp, sizeof(char), desiredBytes, handle->stream);
         break;
     default:
@@ -531,7 +536,8 @@
         break;
     case SF_FORMAT_PCM_16:
         handle->temp = realloc(handle->temp, desiredBytes);
-        memcpy_to_i16_from_float((short *) handle->temp, ptr, desiredFrames);
+        memcpy_to_i16_from_float((short *) handle->temp, ptr,
+                desiredFrames * handle->info.channels);
         actualBytes = fwrite(handle->temp, sizeof(char), desiredBytes, handle->stream);
         break;
     case SF_FORMAT_PCM_U8:  // transcoding from float to byte not yet implemented