1 /* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12
read_raw(const char * filename,size_t * frames)13 float *read_raw(const char *filename, size_t *frames)
14 {
15 struct stat st;
16 int16_t *buf;
17 size_t f, n;
18 int fd;
19 float *data;
20 int i;
21
22 if (stat(filename, &st) < 0) {
23 fprintf(stderr, "cannot stat file %s\n", filename);
24 return NULL;
25 }
26
27 fd = open(filename, O_RDONLY);
28 if (fd < 0) {
29 fprintf(stderr, "cannot open file %s\n", filename);
30 return NULL;
31 }
32
33 f = st.st_size / 4;
34 n = f * 4;
35 buf = (int16_t *)malloc(n);
36 if (read(fd, buf, n) != n) {
37 fprintf(stderr, "short read %zu\n", n);
38 free(buf);
39 return NULL;
40 }
41 close(fd);
42
43 /* deinterleave and convert to float */
44 data = (float *)malloc(sizeof(float) * f * 2);
45 for (i = 0; i < f; i++) {
46 data[i] = buf[2*i] / 32768.0f;
47 data[i + f] = buf[2*i+1] / 32768.0f;
48 }
49 free(buf);
50 *frames = f;
51 return data;
52 }
53
f2s16(float f)54 static int16_t f2s16(float f)
55 {
56 int i;
57 f *= 32768;
58 i = (int)((f > 0) ? (f + 0.5f) : (f - 0.5f));
59 if (i < -32768)
60 i = -32768;
61 else if (i > 32767)
62 i = 32767;
63 return (int16_t)i;
64 }
65
write_raw(const char * filename,float * input,size_t frames)66 int write_raw(const char *filename, float *input, size_t frames)
67 {
68 int16_t *buf;
69 int rc = -1;
70 int n = frames * 4;
71 int i;
72
73 buf = (int16_t *)malloc(n);
74 for (i = 0; i < frames; i++) {
75 buf[2*i] = f2s16(input[i]);
76 buf[2*i+1] = f2s16(input[i + frames]);
77 }
78
79 int fd = open(filename, O_WRONLY | O_CREAT, 0644);
80 if (fd < 0) {
81 fprintf(stderr, "cannot open file %s\n", filename);
82 goto quit;
83 }
84 if (write(fd, buf, n) != n) {
85 fprintf(stderr, "short write file %s\n", filename);
86 goto quit;
87 }
88 rc = 0;
89 quit:
90 close(fd);
91 free(buf);
92 return rc;
93 }
94