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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
|
/*
Copyright (C) 2000 Stefan Westerfeld
[email protected]
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h> // Needed on some systems.
#endif
#ifdef HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
#endif
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <cstring>
#include "debug.h"
#include "audiosubsys.h"
#include "audioio.h"
#define DEFAULT_DEVICE_NAME "/dev/dsp"
#undef DEBUG_WAVEFORM
#ifdef DEBUG_WAVEFORM
#include <fstream>
#endif
using namespace std;
using namespace Arts;
//--- automatic startup class
static AudioSubSystemStart aStart;
void AudioSubSystemStart::startup()
{
_instance = new AudioSubSystem();
}
void AudioSubSystemStart::shutdown()
{
delete _instance;
}
//--- AudioSubSystemPrivate data
class Arts::AudioSubSystemPrivate
{
public:
#ifdef DEBUG_WAVEFORM
ofstream plotfile;
#endif
AudioIO *audioIO;
string audioIOName;
bool audioIOInit;
unsigned int adjustDuplexOffsetIndex;
int adjustDuplexOffset[4];
int adjustDuplexCount;
};
//--- AudioSubSystem implementation
AudioSubSystem *AudioSubSystem::the()
{
return aStart.the();
}
const char *AudioSubSystem::error()
{
return _error.c_str();
}
AudioSubSystem::AudioSubSystem()
{
d = new AudioSubSystemPrivate;
#ifdef DEBUG_WAVEFORM
d->plotfile.open( "/dev/shm/audiosubsystem.plot" );
#endif
d->audioIO = 0;
d->audioIOInit = false;
_running = false;
consumer = 0;
producer = 0;
fragment_buffer = 0;
}
AudioSubSystem::~AudioSubSystem()
{
delete d->audioIO;
delete d;
}
bool AudioSubSystem::attachProducer(ASProducer *producer)
{
assert(producer);
if(this->producer) return false;
this->producer = producer;
return true;
}
bool AudioSubSystem::attachConsumer(ASConsumer *consumer)
{
assert(consumer);
if(this->consumer) return false;
this->consumer = consumer;
return true;
}
void AudioSubSystem::detachProducer()
{
assert(producer);
producer = 0;
if(_running) close();
}
void AudioSubSystem::detachConsumer()
{
assert(consumer);
consumer = 0;
if(_running) close();
}
/* initially creates default AudioIO */
void AudioSubSystem::initAudioIO()
{
/* auto detect */
if(!d->audioIOInit)
{
string bestName;
int bestValue = 0;
arts_debug("autodetecting driver: ");
for(int i = 0; i < AudioIO::queryAudioIOCount(); i++)
{
string name = AudioIO::queryAudioIOParamStr(i, AudioIO::name);
AudioIO *aio = AudioIO::createAudioIO(name.c_str());
int value = aio->getParam(AudioIO::autoDetect);
arts_debug(" - %s: %d", name.c_str(), value);
if(value > bestValue)
{
bestName = name;
bestValue = value;
}
delete aio;
}
if(bestValue)
{
arts_debug("... which means we'll default to %s", bestName.c_str());
audioIO(bestName);
}
else
{
arts_debug("... nothing we could use as default found");
}
}
}
void AudioSubSystem::audioIO(const string& audioIO)
{
if(d->audioIO)
delete d->audioIO;
d->audioIOName = audioIO;
d->audioIO = AudioIO::createAudioIO(audioIO.c_str());
d->audioIOInit = true;
}
string AudioSubSystem::audioIO()
{
initAudioIO();
return d->audioIOName;
}
void AudioSubSystem::deviceName(const string& deviceName)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParamStr(AudioIO::deviceName, deviceName.c_str());
}
string AudioSubSystem::deviceName()
{
initAudioIO();
if(!d->audioIO) return "";
return d->audioIO->getParamStr(AudioIO::deviceName);
}
void AudioSubSystem::fragmentCount(int fragmentCount)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParam(AudioIO::fragmentCount, fragmentCount);
}
int AudioSubSystem::fragmentCount()
{
initAudioIO();
if(!d->audioIO) return 0;
return d->audioIO->getParam(AudioIO::fragmentCount);
}
void AudioSubSystem::fragmentSize(int fragmentSize)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParam(AudioIO::fragmentSize, fragmentSize);
}
int AudioSubSystem::fragmentSize()
{
initAudioIO();
if(!d->audioIO) return 0;
return d->audioIO->getParam(AudioIO::fragmentSize);
}
void AudioSubSystem::samplingRate(int samplingRate)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParam(AudioIO::samplingRate, samplingRate);
}
int AudioSubSystem::samplingRate()
{
initAudioIO();
if(!d->audioIO) return 0;
return d->audioIO->getParam(AudioIO::samplingRate);
}
void AudioSubSystem::channels(int channels)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParam(AudioIO::channels, channels);
}
int AudioSubSystem::channels()
{
initAudioIO();
if(!d->audioIO) return 0;
return d->audioIO->getParam(AudioIO::channels);
}
void AudioSubSystem::format(int format)
{
initAudioIO();
if(!d->audioIO) return;
d->audioIO->setParam(AudioIO::format, format);
}
int AudioSubSystem::format()
{
initAudioIO();
if(!d->audioIO) return 0;
return d->audioIO->getParam(AudioIO::format);
}
int AudioSubSystem::bits()
{
int _format = format();
arts_assert(_format == 0 || _format == 8 || _format == 16 || _format == 17 || _format == 32);
return (_format & (32 | 16 | 8));
}
void AudioSubSystem::fullDuplex(bool fullDuplex)
{
initAudioIO();
if(!d->audioIO) return;
int direction = fullDuplex?3:2;
d->audioIO->setParam(AudioIO::direction, direction);
}
bool AudioSubSystem::fullDuplex()
{
initAudioIO();
if(!d->audioIO) return false;
return d->audioIO->getParam(AudioIO::direction) == 3;
}
int AudioSubSystem::selectReadFD()
{
initAudioIO();
if(!d->audioIO) return false;
return d->audioIO->getParam(AudioIO::selectReadFD);
}
int AudioSubSystem::selectWriteFD()
{
initAudioIO();
if(!d->audioIO) return false;
return d->audioIO->getParam(AudioIO::selectWriteFD);
}
bool AudioSubSystem::check()
{
bool ok = open();
if(ok) close();
return ok;
}
bool AudioSubSystem::open()
{
assert(!_running);
initAudioIO();
if(!d->audioIO)
{
if(d->audioIOName.empty())
_error = "couldn't auto detect which audio I/O method to use";
else
_error = "unable to select '"+d->audioIOName+"' style audio I/O";
return false;
}
if(d->audioIO->open())
{
_running = true;
_fragmentSize = d->audioIO->getParam(AudioIO::fragmentSize);
_fragmentCount = d->audioIO->getParam(AudioIO::fragmentCount);
// allocate global buffer to do I/O
assert(fragment_buffer == 0);
fragment_buffer = new char[_fragmentSize];
d->adjustDuplexCount = 0;
return true;
}
else
{
_error = d->audioIO->getParamStr(AudioIO::lastError);
return false;
}
}
void AudioSubSystem::close()
{
assert(_running);
assert(d->audioIO);
d->audioIO->close();
wBuffer.clear();
rBuffer.clear();
_running = false;
if(fragment_buffer)
{
delete[] fragment_buffer;
fragment_buffer = 0;
}
}
bool AudioSubSystem::running()
{
return _running;
}
void AudioSubSystem::handleIO(int type)
{
assert(d->audioIO);
if(type & ioRead)
{
int len = d->audioIO->read(fragment_buffer,_fragmentSize);
if(len > 0)
{
if(rBuffer.size() < _fragmentSize * _fragmentCount * bits() / 8 * channels())
{
rBuffer.write(len,fragment_buffer);
#ifdef DEBUG_WAVEFORM
float * end = (float *)(fragment_buffer + len);
float * floatbuffer = (float *)fragment_buffer;
while(floatbuffer < end)
{
d->plotfile << *floatbuffer++ << "\n";
++floatbuffer;
}
#endif
}
else
{
arts_debug( "AudioSubSystem: rBuffer is too full" );
}
}
}
if(type & ioWrite)
{
/*
* make sure that we have a fragment full of data at least
*/
Rewrite:
while(wBuffer.size() < _fragmentSize)
{
long wbsz = wBuffer.size();
producer->needMore();
if(wbsz == wBuffer.size())
{
/*
* Even though we asked the client to supply more
* data, he didn't give us more. So we can't supply
* output data as well. Bad luck. Might produce a
* buffer underrun - but we can't help here.
*/
arts_info("full duplex: no more data available (underrun)");
return;
}
}
/*
* look how much we really can write without blocking
*/
int space = d->audioIO->getParam(AudioIO::canWrite);
int can_write = min(space, _fragmentSize);
if(can_write > 0)
{
/*
* ok, so write it (as we checked that our buffer has enough data
* to do so and the soundcardbuffer has enough data to handle this
* write, nothing can go wrong here)
*/
int rSize = wBuffer.read(can_write,fragment_buffer);
assert(rSize == can_write);
int len = d->audioIO->write(fragment_buffer,can_write);
if(len != can_write)
arts_fatal("AudioSubSystem::handleIO: write failed\n"
"len = %d, can_write = %d, errno = %d (%s)\n\n"
"This might be a sound hardware/driver specific problem"
" (see aRts FAQ)",len,can_write,errno,strerror(errno));
if(fullDuplex())
{
/*
* if we're running full duplex, here is a good place to check
* for full duplex drift
*/
d->adjustDuplexCount += can_write;
if(d->adjustDuplexCount > samplingRate())
{
adjustDuplexBuffers();
d->adjustDuplexCount = 0;
}
}
}
// If we can write a fragment more, then do so right now:
if (space >= _fragmentSize*2) goto Rewrite;
}
assert((type & ioExcept) == 0);
}
void AudioSubSystem::read(void *buffer, int size)
{
/* if not enough data can be read, produce some */
while(rBuffer.size() < size)
adjustInputBuffer(1);
/* finally, just take the data out of the input buffer */
int rSize = rBuffer.read(size,buffer);
assert(rSize == size);
}
void AudioSubSystem::write(void *buffer, int size)
{
wBuffer.write(size,buffer);
}
float AudioSubSystem::outputDelay()
{
int fsize = _fragmentSize;
int fcount = _fragmentCount;
if(fsize > 0 && fcount > 0) // not all AudioIO classes need to support this
{
double hardwareBuffer = fsize * fcount;
double freeOutputSpace = d->audioIO->getParam(AudioIO::canWrite);
double playSpeed = channels() * samplingRate() * (bits() / 8);
return (hardwareBuffer - freeOutputSpace) / playSpeed;
}
else return 0.0;
}
void AudioSubSystem::adjustDuplexBuffers()
{
int fsize = _fragmentSize;
int fcount = _fragmentCount;
if(fsize > 0 && fcount > 0) // not all AudioIO classes need to support this
{
int bound = 2; //max(fcount/2, 1);
int optimalOffset = fsize * (fcount + bound);
int minOffset = fsize * fcount;
int maxOffset = fsize * (fcount + 2 * bound);
int canRead = d->audioIO->getParam(AudioIO::canRead);
if(canRead < 0)
{
arts_warning("AudioSubSystem::adjustDuplexBuffers: canRead < 0?");
canRead = 0;
}
int canWrite = d->audioIO->getParam(AudioIO::canWrite);
if(canWrite < 0)
{
arts_warning("AudioSubSystem::adjustDuplexBuffers: canWrite < 0?");
canWrite = 0;
}
int currentOffset = rBuffer.size() + wBuffer.size()
+ canRead + max((fsize * fcount) - canWrite, 0);
d->adjustDuplexOffset[d->adjustDuplexOffsetIndex++ & 3] = currentOffset;
if(d->adjustDuplexOffsetIndex <= 4) return;
int avgOffset;
avgOffset = d->adjustDuplexOffset[0]
+ d->adjustDuplexOffset[1]
+ d->adjustDuplexOffset[2]
+ d->adjustDuplexOffset[3];
avgOffset /= 4;
/*
printf("offset: %d avg %d min %d opt %d max %d\r", currentOffset,
avgOffset, minOffset, optimalOffset, maxOffset);
fflush(stdout);
*/
if(minOffset <= avgOffset && avgOffset <= maxOffset)
return;
d->adjustDuplexOffsetIndex = 0;
int adjust = (optimalOffset - currentOffset) / _fragmentSize;
arts_debug("AudioSubSystem::adjustDuplexBuffers(%d)", adjust);
}
}
void AudioSubSystem::adjustInputBuffer(int count)
{
if(format() == 8)
{
memset( fragment_buffer, 0x80, _fragmentSize );
}
else
{
memset( fragment_buffer, 0, _fragmentSize );
}
while(count > 0 && rBuffer.size() < _fragmentSize * _fragmentCount * 4)
{
rBuffer.write(_fragmentSize, fragment_buffer);
#ifdef DEBUG_WAVEFORM
float * end = (float *)(fragment_buffer + _fragmentSize);
float * floatbuffer = (float *)fragment_buffer;
while(floatbuffer < end)
{
d->plotfile << *floatbuffer++ << "\n";
++floatbuffer;
}
#endif
count--;
}
while(count < 0 && rBuffer.size() >= _fragmentSize)
{
rBuffer.read(_fragmentSize, fragment_buffer);
count++;
}
}
void AudioSubSystem::emergencyCleanup()
{
if(producer || consumer)
{
fprintf(stderr, "AudioSubSystem::emergencyCleanup\n");
if(producer)
detachProducer();
if(consumer)
detachConsumer();
}
}
|