-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathAudioOutput.cc
More file actions
348 lines (273 loc) · 8.75 KB
/
Copy pathAudioOutput.cc
File metadata and controls
348 lines (273 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
* Audio output handling for SoftFM
*
* Copyright (C) 2013, Joris van Rantwijk.
*
* .WAV file writing by Sidney Cadot,
* adapted for SoftFM by Joris van Rantwijk.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/gpl-2.0.html
*/
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <algorithm>
#include <alsa/asoundlib.h>
#include "SoftFM.h"
#include "AudioOutput.h"
using namespace std;
/* **************** class AudioOutput **************** */
// Encode a list of samples as signed 16-bit little-endian integers.
void AudioOutput::samplesToInt16(const SampleVector& samples,
vector<uint8_t>& bytes)
{
bytes.resize(2 * samples.size());
SampleVector::const_iterator i = samples.begin();
SampleVector::const_iterator n = samples.end();
vector<uint8_t>::iterator k = bytes.begin();
while (i != n) {
Sample s = *(i++);
s = max(Sample(-1.0), min(Sample(1.0), s));
long v = lrint(s * 32767);
unsigned long u = v;
*(k++) = u & 0xff;
*(k++) = (u >> 8) & 0xff;
}
}
/* **************** class RawAudioOutput **************** */
// Construct raw audio writer.
RawAudioOutput::RawAudioOutput(const string& filename)
{
if (filename == "-") {
m_fd = STDOUT_FILENO;
} else {
m_fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (m_fd < 0) {
m_error = "can not open '" + filename + "' (" +
strerror(errno) + ")";
m_zombie = true;
return;
}
}
}
// Destructor.
RawAudioOutput::~RawAudioOutput()
{
// Close file descriptor.
if (m_fd >= 0 && m_fd != STDOUT_FILENO) {
close(m_fd);
}
}
// Write audio data.
bool RawAudioOutput::write(const SampleVector& samples)
{
if (m_fd < 0)
return false;
// Convert samples to bytes.
samplesToInt16(samples, m_bytebuf);
// Write data.
size_t p = 0;
size_t n = m_bytebuf.size();
while (p < n) {
ssize_t k = ::write(m_fd, m_bytebuf.data() + p, n - p);
if (k <= 0) {
if (k == 0 || errno != EINTR) {
m_error = "write failed (";
m_error += strerror(errno);
m_error += ")";
return false;
}
} else {
p += k;
}
}
return true;
}
/* **************** class WavAudioOutput **************** */
// Construct .WAV writer.
WavAudioOutput::WavAudioOutput(const std::string& filename,
unsigned int samplerate,
bool stereo)
: numberOfChannels(stereo ? 2 : 1)
, sampleRate(samplerate)
{
m_stream = fopen(filename.c_str(), "wb");
if (m_stream == NULL) {
m_error = "can not open '" + filename + "' (" +
strerror(errno) + ")";
m_zombie = true;
return;
}
// Write initial header with a dummy sample count.
// This will be replaced with the actual header once the WavFile is closed.
if (!write_header(0x7fff0000)) {
m_error = "can not write to '" + filename + "' (" +
strerror(errno) + ")";
m_zombie = true;
}
}
// Destructor.
WavAudioOutput::~WavAudioOutput()
{
// We need to go back and fill in the header ...
if (!m_zombie) {
const unsigned bytesPerSample = 2;
const long currentPosition = ftell(m_stream);
assert((currentPosition - 44) % bytesPerSample == 0);
const unsigned totalNumberOfSamples = (currentPosition - 44) / bytesPerSample;
assert(totalNumberOfSamples % numberOfChannels == 0);
// Put header in front
if (fseek(m_stream, 0, SEEK_SET) == 0) {
write_header(totalNumberOfSamples);
}
}
// Done writing the file
if (m_stream) {
fclose(m_stream);
}
}
// Write audio data.
bool WavAudioOutput::write(const SampleVector& samples)
{
if (m_zombie)
return false;
// Convert samples to bytes.
samplesToInt16(samples, m_bytebuf);
// Write samples to file.
size_t k = fwrite(m_bytebuf.data(), 1, m_bytebuf.size(), m_stream);
if (k != m_bytebuf.size()) {
m_error = "write failed (";
m_error += strerror(errno);
m_error += ")";
return false;
}
return true;
}
// (Re)write .WAV header.
bool WavAudioOutput::write_header(unsigned int nsamples)
{
const unsigned bytesPerSample = 2;
const unsigned bitsPerSample = 16;
enum wFormatTagId
{
WAVE_FORMAT_PCM = 0x0001,
WAVE_FORMAT_IEEE_FLOAT = 0x0003
};
assert(nsamples % numberOfChannels == 0);
// synthesize header
uint8_t wavHeader[44];
encode_chunk_id (wavHeader + 0, "RIFF");
set_value<uint32_t>(wavHeader + 4, 36 + nsamples * bytesPerSample);
encode_chunk_id (wavHeader + 8, "WAVE");
encode_chunk_id (wavHeader + 12, "fmt ");
set_value<uint32_t>(wavHeader + 16, 16);
set_value<uint16_t>(wavHeader + 20, WAVE_FORMAT_PCM);
set_value<uint16_t>(wavHeader + 22, numberOfChannels);
set_value<uint32_t>(wavHeader + 24, sampleRate ); // sample rate
set_value<uint32_t>(wavHeader + 28, sampleRate * numberOfChannels * bytesPerSample); // byte rate
set_value<uint16_t>(wavHeader + 32, numberOfChannels * bytesPerSample); // block size
set_value<uint16_t>(wavHeader + 34, bitsPerSample);
encode_chunk_id (wavHeader + 36, "data");
set_value<uint32_t>(wavHeader + 40, nsamples * bytesPerSample);
return fwrite(wavHeader, 1, 44, m_stream) == 44;
}
void WavAudioOutput::encode_chunk_id(uint8_t * ptr, const char * chunkname)
{
for (unsigned i = 0; i < 4; ++i)
{
assert(chunkname[i] != '\0');
ptr[i] = chunkname[i];
}
assert(chunkname[4] == '\0');
}
template <typename T>
void WavAudioOutput::set_value(uint8_t * ptr, T value)
{
for (size_t i = 0; i < sizeof(T); ++i)
{
ptr[i] = value & 0xff;
value >>= 8;
}
}
/* **************** class AlsaAudioOutput **************** */
// Construct ALSA output stream.
AlsaAudioOutput::AlsaAudioOutput(const std::string& devname,
unsigned int samplerate,
bool stereo)
{
m_pcm = NULL;
m_nchannels = stereo ? 2 : 1;
int r = snd_pcm_open(&m_pcm, devname.c_str(),
SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
if (r < 0) {
m_error = "can not open PCM device '" + devname + "' (" +
strerror(-r) + ")";
m_zombie = true;
return;
}
snd_pcm_nonblock(m_pcm, 0);
r = snd_pcm_set_params(m_pcm,
SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED,
m_nchannels,
samplerate,
1, // allow soft resampling
500000); // latency in us
if (r < 0) {
m_error = "can not set PCM parameters (";
m_error += strerror(-r);
m_error += ")";
m_zombie = true;
}
}
// Destructor.
AlsaAudioOutput::~AlsaAudioOutput()
{
// Close device.
if (m_pcm != NULL) {
snd_pcm_close(m_pcm);
}
}
// Write audio data.
bool AlsaAudioOutput::write(const SampleVector& samples)
{
if (m_zombie)
return false;
// Convert samples to bytes.
samplesToInt16(samples, m_bytebuf);
// Write data.
unsigned int p = 0;
unsigned int n = samples.size() / m_nchannels;
unsigned int framesize = 2 * m_nchannels;
while (p < n) {
int k = snd_pcm_writei(m_pcm,
m_bytebuf.data() + p * framesize, n - p);
if (k < 0) {
m_error = "write failed (";
m_error += strerror(errno);
m_error += ")";
// After an underrun, ALSA keeps returning error codes until we
// explicitly fix the stream.
snd_pcm_recover(m_pcm, k, 0);
return false;
} else {
p += k;
}
}
return true;
}
/* end */