summaryrefslogtreecommitdiff
path: root/portaudio/src/hostapi/oss/pa_unix_oss.c
blob: 20113e23f1a3b2c2aeca87682ba0b14a253f9b5b (plain)
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
/*
 * $Id$
 * PortAudio Portable Real-Time Audio Library
 * Latest Version at: http://www.portaudio.com
 * OSS implementation by:
 *   Douglas Repetto
 *   Phil Burk
 *   Dominic Mazzoni
 *   Arve Knudsen
 *
 * Based on the Open Source API proposed by Ross Bencina
 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * The text above constitutes the entire PortAudio license; however,
 * the PortAudio community also makes the following non-binding requests:
 *
 * Any person wishing to distribute modifications to the Software is
 * requested to send the modifications to the original developer so that
 * they can be incorporated into the canonical version. It is also
 * requested that these non-binding requests be included along with the
 * license above.
 */

/**
 @file
 @ingroup hostapi_src
*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/poll.h>
#include <limits.h>
#include <semaphore.h>

#ifdef HAVE_SYS_SOUNDCARD_H
# include <sys/soundcard.h>
# ifdef __NetBSD__
#  define DEVICE_NAME_BASE           "/dev/audio"
# else
#  define DEVICE_NAME_BASE           "/dev/dsp"
# endif
#elif defined(HAVE_LINUX_SOUNDCARD_H)
# include <linux/soundcard.h>
# define DEVICE_NAME_BASE            "/dev/dsp"
#elif defined(HAVE_MACHINE_SOUNDCARD_H)
# include <machine/soundcard.h> /* JH20010905 */
# define DEVICE_NAME_BASE            "/dev/audio"
#else
# error No sound card header file
#endif

#include "portaudio.h"
#include "pa_util.h"
#include "pa_allocation.h"
#include "pa_hostapi.h"
#include "pa_stream.h"
#include "pa_cpuload.h"
#include "pa_process.h"
#include "pa_unix_util.h"
#include "pa_debugprint.h"

static int sysErr_;
static pthread_t mainThread_;

/* Check return value of system call, and map it to PaError */
#define ENSURE_(expr, code) \
    do { \
        if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \
        { \
            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
            if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
            { \
                PaUtil_SetLastHostErrorInfo( paOSS, sysErr_, strerror( errno ) ); \
            } \
            \
            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
            result = (code); \
            goto error; \
        } \
    } while( 0 );

#ifndef AFMT_S16_NE
#define AFMT_S16_NE  Get_AFMT_S16_NE()
/*********************************************************************
 * Some versions of OSS do not define AFMT_S16_NE. So check CPU.
 * PowerPC is Big Endian. X86 is Little Endian.
 */
static int Get_AFMT_S16_NE( void )
{
    long testData = 1;
    char *ptr = (char *) &testData;
    int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */
    return isLittle ? AFMT_S16_LE : AFMT_S16_BE;
}
#endif

/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */

typedef struct
{
    PaUtilHostApiRepresentation inheritedHostApiRep;
    PaUtilStreamInterface callbackStreamInterface;
    PaUtilStreamInterface blockingStreamInterface;

    PaUtilAllocationGroup *allocations;

    PaHostApiIndex hostApiIndex;
}
PaOSSHostApiRepresentation;

/** Per-direction structure for PaOssStream.
 *
 * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,
 * but with different number of channels we will have to adapt between the number of user and host
 * channels for at least one direction, since the configuration space is the same for both directions
 * of an OSS device.
 */
typedef struct
{
    int fd;
    const char *devName;
    int userChannelCount, hostChannelCount;
    int userInterleaved;
    void *buffer;
    PaSampleFormat userFormat, hostFormat;
    double latency;
    unsigned long hostFrames, numBufs;
    void **userBuffers; /* For non-interleaved blocking */
} PaOssStreamComponent;

/** Implementation specific representation of a PaStream.
 *
 */
typedef struct PaOssStream
{
    PaUtilStreamRepresentation streamRepresentation;
    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
    PaUtilBufferProcessor bufferProcessor;

    PaUtilThreading threading;

    int sharedDevice;
    unsigned long framesPerHostBuffer;
    int triggered;  /* Have the devices been triggered yet (first start) */

    int isActive;
    int isStopped;

    int lastPosPtr;
    double lastStreamBytes;

    int framesProcessed;

    double sampleRate;

    int callbackMode;
    volatile int callbackStop, callbackAbort;

    PaOssStreamComponent *capture, *playback;
    unsigned long pollTimeout;
    sem_t semaphore;
}
PaOssStream;

typedef enum {
    StreamMode_In,
    StreamMode_Out
} StreamMode;

/* prototypes for functions declared in this file */

static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate );
static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** s,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
                           unsigned long framesPerBuffer,
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData );
static PaError CloseStream( PaStream* stream );
static PaError StartStream( PaStream *stream );
static PaError StopStream( PaStream *stream );
static PaError AbortStream( PaStream *stream );
static PaError IsStreamStopped( PaStream *s );
static PaError IsStreamActive( PaStream *stream );
static PaTime GetStreamTime( PaStream *stream );
static double GetStreamCpuLoad( PaStream* stream );
static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
static signed long GetStreamReadAvailable( PaStream* stream );
static signed long GetStreamWriteAvailable( PaStream* stream );
static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );


/** Initialize the OSS API implementation.
 *
 * This function will initialize host API datastructures and query host devices for information.
 *
 * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here
 *
 * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,
 * this happens with the usual "error" label.
 */
PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
{
    PaError result = paNoError;
    PaOSSHostApiRepresentation *ossHostApi = NULL;

    PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),
            paInsufficientMemory );
    PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
    ossHostApi->hostApiIndex = hostApiIndex;

    /* Initialize host API structure */
    *hostApi = &ossHostApi->inheritedHostApiRep;
    (*hostApi)->info.structVersion = 1;
    (*hostApi)->info.type = paOSS;
    (*hostApi)->info.name = "OSS";
    (*hostApi)->Terminate = Terminate;
    (*hostApi)->OpenStream = OpenStream;
    (*hostApi)->IsFormatSupported = IsFormatSupported;

    PA_ENSURE( BuildDeviceList( ossHostApi ) );

    PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
                                      GetStreamTime, GetStreamCpuLoad,
                                      PaUtil_DummyRead, PaUtil_DummyWrite,
                                      PaUtil_DummyGetReadAvailable,
                                      PaUtil_DummyGetWriteAvailable );

    PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );

    mainThread_ = pthread_self();

    return result;

error:
    if( ossHostApi )
    {
        if( ossHostApi->allocations )
        {
            PaUtil_FreeAllAllocations( ossHostApi->allocations );
            PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
        }

        PaUtil_FreeMemory( ossHostApi );
    }
    return result;
}

PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,
        int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,
        PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations  )
{
    PaError result = paNoError;

    deviceInfo->structVersion = 2;
    if( allocations )
    {
        size_t len = strlen( name ) + 1;
        PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );
        strncpy( (char *)deviceInfo->name, name, len );
    }
    else
        deviceInfo->name = name;

    deviceInfo->hostApi = hostApiIndex;
    deviceInfo->maxInputChannels = maxInputChannels;
    deviceInfo->maxOutputChannels = maxOutputChannels;
    deviceInfo->defaultLowInputLatency = defaultLowInputLatency;
    deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;
    deviceInfo->defaultHighInputLatency = defaultHighInputLatency;
    deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;
    deviceInfo->defaultSampleRate = defaultSampleRate;

error:
    return result;
}

static int CalcHigherLogTwo( int n )
{
    int log2 = 0;
    while( (1<<log2) < n ) log2++;
    return log2;
}

static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,
        double *defaultLowLatency, double *defaultHighLatency )
{
    PaError result = paNoError;
    int numChannels, maxNumChannels;
    int busy = 0;
    int devHandle = -1;
    int sr;
    *maxChannelCount = 0;  /* Default value in case this fails */
    int temp, frgmt;
    unsigned long fragFrames;

    if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK ))  < 0 )
    {
        if( errno == EBUSY || errno == EAGAIN )
        {
            PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));
        }
        else
        {
            /* Ignore ENOENT, which means we've tried a non-existent device */
            if( errno != ENOENT )
            {
                PA_DEBUG(( "%s: Can't access device %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
            }
        }

        return paDeviceUnavailable;
    }

    /* Negotiate for the maximum number of channels for this device. PLB20010927
     * Consider up to 16 as the upper number of channels.
     * Variable maxNumChannels should contain the actual upper limit after the call.
     * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
     */
    maxNumChannels = 0;
    for( numChannels = 1; numChannels <= 16; numChannels++ )
    {
        temp = numChannels;
        if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )
        {
            busy = EAGAIN == errno || EBUSY == errno;
            /* ioctl() failed so bail out if we already have stereo */
            if( maxNumChannels >= 2 )
                break;
        }
        else
        {
            /* ioctl() worked but bail out if it does not support numChannels.
             * We don't want to leave gaps in the numChannels supported.
             */
            if( (numChannels > 2) && (temp != numChannels) )
                break;
            if( temp > maxNumChannels )
                maxNumChannels = temp; /* Save maximum. */
        }
    }
    /* A: We're able to open a device for capture if it's busy playing back and vice versa,
     * but we can't configure anything */
    if( 0 == maxNumChannels && busy )
    {
        result = paDeviceUnavailable;
        goto error;
    }

    /* The above negotiation may fail for an old driver so try this older technique. */
    if( maxNumChannels < 1 )
    {
        int stereo = 1;
        if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )
        {
            maxNumChannels = 1;
        }
        else
        {
            maxNumChannels = (stereo) ? 2 : 1;
        }
        PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ));
    }

    /* During channel negotiation, the last ioctl() may have failed. This can
     * also cause sample rate negotiation to fail. Hence the following, to return
     * to a supported number of channels. SG20011005 */
    {
        /* use most reasonable default value */
        numChannels = PA_MIN( maxNumChannels, 2 );
        ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &numChannels ), paUnanticipatedHostError );
    }

    /* Get supported sample rate closest to 44100 Hz */
    if( *defaultSampleRate < 0 )
    {
        sr = 44100;
        ENSURE_( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ), paUnanticipatedHostError );

        *defaultSampleRate = sr;
    }

    *maxChannelCount = maxNumChannels;

    /* Attempt to set low latency with 4 frags-per-buffer, 128 frames-per-frag (total buffer 512 frames)
     * since the ioctl sets bytes, multiply by numChannels, and base on 2 bytes-per-sample, */
    fragFrames = 128;
    frgmt = (4 << 16) + (CalcHigherLogTwo( fragFrames * numChannels * 2 ) & 0xffff);
    ENSURE_( ioctl( devHandle, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );

    /* Use the value set by the ioctl to give the latency achieved */
    fragFrames = pow( 2, frgmt & 0xffff ) / (numChannels * 2);
    *defaultLowLatency = ((frgmt >> 16) - 1) * fragFrames / *defaultSampleRate;

    /* Cannot now try setting a high latency (device would need closing and opening again).  Make
     * high-latency 4 times the low unless the fragFrames are significantly more than requested 128 */
    temp = (fragFrames < 256) ? 4 : (fragFrames < 512) ? 2 : 1;
    *defaultHighLatency = temp * *defaultLowLatency;

error:
    if( devHandle >= 0 )
        close( devHandle );

    return result;
}

/** Query OSS device.
 *
 * This is where PaDeviceInfo objects are constructed and filled in with relevant information.
 *
 * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed
 * in place.
 */
static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )
{
    PaError result = paNoError;
    double sampleRate = -1.;
    int maxInputChannels, maxOutputChannels;
    PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;
    PaError tmpRes = paNoError;
    int busy = 0;
    *deviceInfo = NULL;

    /* douglas:
       we have to do this querying in a slightly different order. apparently
       some sound cards will give you different info based on their settings.
       e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
       the correct order for OSS is: format, channels, sample rate
    */

    /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is
     * opened in, it may have more channels available for capture than playback and vice versa. Therefore
     * we will open the device in both read- and write-only mode to determine the supported number.
     */
    if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,
                &defaultHighInputLatency )) != paNoError )
    {
        if( tmpRes != paDeviceUnavailable )
        {
            PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));
            /* PA_ENSURE( tmpRes ); */
        }
        ++busy;
    }
    if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,
                &defaultHighOutputLatency )) != paNoError )
    {
        if( tmpRes != paDeviceUnavailable )
        {
            PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));
            /* PA_ENSURE( tmpRes ); */
        }
        ++busy;
    }
    assert( 0 <= busy && busy <= 2 );
    if( 2 == busy )     /* Both directions are unavailable to us */
    {
        result = paDeviceUnavailable;
        goto error;
    }

    PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );
    PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,
                defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,
                ossApi->allocations ) );

error:
    return result;
}

/** Query host devices.
 *
 * Loop over host devices and query their capabilitiesu
 *
 * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object
 * per device, these are placed in the host api representation's deviceInfos array.
 */
static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
{
    PaError result = paNoError;
    PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;
    int i;
    int numDevices = 0, maxDeviceInfos = 1;
    PaDeviceInfo **deviceInfos = NULL;

    /* These two will be set to the first working input and output device, respectively */
    commonApi->info.defaultInputDevice = paNoDevice;
    commonApi->info.defaultOutputDevice = paNoDevice;

    /* Find devices by calling QueryDevice on each
     * potential device names.  When we find a valid one,
     * add it to a linked list.
     * A: Set an arbitrary of 100 devices, should probably be a smarter way. */

    for( i = -1; i < 100; i++ )
    {
        char deviceName[32];
        PaDeviceInfo *deviceInfo;
        int testResult;

        if( i == -1 )
            snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
        else
            snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);

        /* PA_DEBUG(("%s: trying device %s\n", __FUNCTION__, deviceName )); */
        if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
        {
            if( testResult != paDeviceUnavailable )
                PA_ENSURE( testResult );

            continue;
        }

        ++numDevices;
        if( !deviceInfos || numDevices > maxDeviceInfos )
        {
            maxDeviceInfos *= 2;
            PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),
                    paInsufficientMemory );
        }
        {
            int devIdx = numDevices - 1;
            deviceInfos[devIdx] = deviceInfo;

            if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )
                commonApi->info.defaultInputDevice = devIdx;
            if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )
                commonApi->info.defaultOutputDevice = devIdx;
        }
    }

    /* Make an array of PaDeviceInfo pointers out of the linked list */

    PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));

    commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
        ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
    memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );

    commonApi->info.deviceCount = numDevices;

error:
    free( deviceInfos );

    return result;
}

static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
{
    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;

    if( ossHostApi->allocations )
    {
        PaUtil_FreeAllAllocations( ossHostApi->allocations );
        PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
    }

    PaUtil_FreeMemory( ossHostApi );
}

static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate )
{
    PaError result = paNoError;
    PaDeviceIndex device;
    PaDeviceInfo *deviceInfo;
    char *deviceName;
    int inputChannelCount, outputChannelCount;
    int tempDevHandle = -1;
    int flags;
    PaSampleFormat inputSampleFormat, outputSampleFormat;

    if( inputParameters )
    {
        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;

        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that input device can support inputChannelCount */
        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
            return paInvalidChannelCount;

        /* validate inputStreamInfo */
        if( inputParameters->hostApiSpecificStreamInfo )
            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
    }
    else
    {
        inputChannelCount = 0;
    }

    if( outputParameters )
    {
        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;

        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that output device can support inputChannelCount */
        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
            return paInvalidChannelCount;

        /* validate outputStreamInfo */
        if( outputParameters->hostApiSpecificStreamInfo )
            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
    }
    else
    {
        outputChannelCount = 0;
    }

    if (inputChannelCount == 0 && outputChannelCount == 0)
        return paInvalidChannelCount;

    /* if full duplex, make sure that they're the same device */

    if (inputChannelCount > 0 && outputChannelCount > 0 &&
            inputParameters->device != outputParameters->device)
        return paInvalidDevice;

    /* if full duplex, also make sure that they're the same number of channels */

    if (inputChannelCount > 0 && outputChannelCount > 0 &&
            inputChannelCount != outputChannelCount)
        return paInvalidChannelCount;

    /* open the device so we can do more tests */

    if( inputChannelCount > 0 )
    {
        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);
        if (result != paNoError)
            return result;
    }
    else
    {
        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);
        if (result != paNoError)
            return result;
    }

    deviceInfo = hostApi->deviceInfos[device];
    deviceName = (char *)deviceInfo->name;

    flags = O_NONBLOCK;
    if (inputChannelCount > 0 && outputChannelCount > 0)
        flags |= O_RDWR;
    else if (inputChannelCount > 0)
        flags |= O_RDONLY;
    else
        flags |= O_WRONLY;

    ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );

    /* PaOssStream_Configure will do the rest of the checking for us */
    /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */

    /* everything succeeded! */

error:
    if( tempDevHandle >= 0 )
        close( tempDevHandle );

    return result;
}

/** Validate stream parameters.
 *
 * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device
 */
static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )
{
    int maxChans;

    assert( parameters );

    if( parameters->device == paUseHostApiSpecificDeviceSpecification )
    {
        return paInvalidDevice;
    }

    maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels : deviceInfo->maxOutputChannels);
    if( parameters->channelCount > maxChans )
    {
        return paInvalidChannelCount;
    }

    return paNoError;
}

static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,
        int callbackMode, int fd, const char *deviceName )
{
    PaError result = paNoError;
    assert( component );

    memset( component, 0, sizeof (PaOssStreamComponent) );

    component->fd = fd;
    component->devName = deviceName;
    component->userChannelCount = parameters->channelCount;
    component->userFormat = parameters->sampleFormat;
    component->latency = parameters->suggestedLatency;
    component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);

    if( !callbackMode && !component->userInterleaved )
    {
        /* Pre-allocate non-interleaved user provided buffers */
        PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),
                paInsufficientMemory );
    }

error:
    return result;
}

static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )
{
    assert( component );

    if( component->fd >= 0 )
        close( component->fd );
    if( component->buffer )
        PaUtil_FreeMemory( component->buffer );

    if( component->userBuffers )
        PaUtil_FreeMemory( component->userBuffers );

    PaUtil_FreeMemory( component );
}

static PaError ModifyBlocking( int fd, int blocking )
{
    PaError result = paNoError;
    int fflags;

    ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );

    if( blocking )
        fflags &= ~O_NONBLOCK;
    else
        fflags |= O_NONBLOCK;

    ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );

error:
    return result;
}

/** Open input and output devices.
 *
 * @param idev: Returned input device file descriptor.
 * @param odev: Returned output device file descriptor.
 */
static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
{
    PaError result = paNoError;
    int flags = O_NONBLOCK, duplex = 0;
    *idev = *odev = -1;

    if( idevName && odevName )
    {
        duplex = 1;
        flags |= O_RDWR;
    }
    else if( idevName )
        flags |= O_RDONLY;
    else
        flags |= O_WRONLY;

    /* open first in nonblocking mode, in case it's busy...
     * A: then unset the non-blocking attribute */
    assert( flags & O_NONBLOCK );
    if( idevName )
    {
        ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
        PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
    }
    if( odevName )
    {
        if( !idevName )
        {
            ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
            PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
        }
        else
        {
            ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );
        }
    }

error:
    return result;
}

static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,
        PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,
        PaOSSHostApiRepresentation *ossApi )
{
    PaError result = paNoError;
    int idev, odev;
    PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;
    const char *idevName = NULL, *odevName = NULL;

    assert( stream );

    memset( stream, 0, sizeof (PaOssStream) );
    stream->isStopped = 1;

    PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );

    if( inputParameters && outputParameters )
    {
        if( inputParameters->device == outputParameters->device )
            stream->sharedDevice = 1;
    }

    if( inputParameters )
        idevName = hostApi->deviceInfos[inputParameters->device]->name;
    if( outputParameters )
        odevName = hostApi->deviceInfos[outputParameters->device]->name;
    PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );
    if( inputParameters )
    {
        PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
        PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );
    }
    if( outputParameters )
    {
        PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
        PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );
    }

    if( callback != NULL )
    {
        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
                                               &ossApi->callbackStreamInterface, callback, userData );
        stream->callbackMode = 1;
    }
    else
    {
        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
                                               &ossApi->blockingStreamInterface, callback, userData );
    }

    ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );

error:
    return result;
}

static void PaOssStream_Terminate( PaOssStream *stream )
{
    assert( stream );

    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
    PaUtil_TerminateThreading( &stream->threading );

    if( stream->capture )
        PaOssStreamComponent_Terminate( stream->capture );
    if( stream->playback )
        PaOssStreamComponent_Terminate( stream->playback );

    sem_destroy( &stream->semaphore );

    PaUtil_FreeMemory( stream );
}

/** Translate from PA format to OSS native.
 *
 */
static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )
{
    switch( paFormat )
    {
        case paUInt8:
            *ossFormat = AFMT_U8;
            break;
        case paInt8:
            *ossFormat = AFMT_S8;
            break;
        case paInt16:
            *ossFormat = AFMT_S16_NE;
            break;
#ifdef AFMT_S32_NE
        case paInt32:
            *ossFormat = AFMT_S32_NE;
            break;
#endif
        default:
            return paInternalError;     /* This shouldn't happen */
    }

    return paNoError;
}

/** Return the PA-compatible formats that this device can support.
 *
 */
static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )
{
    PaError result = paNoError;
    int mask = 0;
    PaSampleFormat frmts = 0;

    ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );
    if( mask & AFMT_U8 )
        frmts |= paUInt8;
    if( mask & AFMT_S8 )
        frmts |= paInt8;
    if( mask & AFMT_S16_NE )
        frmts |= paInt16;
#ifdef AFMT_S32_NE
    if( mask & AFMT_S32_NE )
        frmts |= paInt32;
#endif
    if( frmts == 0 )
        result = paSampleFormatNotSupported;

    *availableFormats = frmts;

error:
    return result;
}

static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )
{
    return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;
}

/** Buffer size in bytes.
 *
 */
static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )
{
    return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;
}

/** Configure stream component device parameters.
 */
static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long
        framesPerBuffer, StreamMode streamMode, PaOssStreamComponent *master )
{
    PaError result = paNoError;
    int temp, nativeFormat;
    int sr = (int)sampleRate;
    PaSampleFormat availableFormats = 0, hostFormat = 0;
    int chans = component->userChannelCount;
    int frgmt;
    int numBufs;
    int bytesPerBuf;
    unsigned long bufSz;
    unsigned long fragSz;
    audio_buf_info bufInfo;

    /* We may have a situation where only one component (the master) is configured, if both point to the same device.
     * In that case, the second component will copy settings from the other */
    if( !master )
    {
        /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.
         * The hardware need not respect the requested fragment size, so we may have to adapt.
         */
        if( framesPerBuffer == paFramesPerBufferUnspecified )
        {
            /* Aim for 4 fragments in the complete buffer; the latency comes from 3 of these */
            fragSz = (unsigned long)(component->latency * sampleRate / 3);
            bufSz = fragSz * 4;
        }
        else
        {
            fragSz = framesPerBuffer;
            bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */
        }

        PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );
        hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );

        /* OSS demands at least 2 buffers, and 16 bytes per buffer */
        numBufs = (int)PA_MAX( bufSz / fragSz, 2 );
        bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );

        /* The fragment parameters are encoded like this:
         * Most significant byte: number of fragments
         * Least significant byte: exponent of fragment size (i.e., for 256, 8)
         */
        frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);
        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );

        /* A: according to the OSS programmer's guide parameters should be set in this order:
         * format, channels, rate */

        /* This format should be deemed good before we get this far */
        PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );
        nativeFormat = temp;
        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );
        PA_UNLESS( temp == nativeFormat, paInternalError );

        /* try to set the number of channels */
        ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported );   /* XXX: Should be paInvalidChannelCount? */
        /* It's possible that the minimum number of host channels is greater than what the user requested */
        PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );

        /* try to set the sample rate */
        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );

        /* reject if there's no sample rate within 1% of the one requested */
        if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )
        {
            PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
            PA_ENSURE( paInvalidSampleRate );
        }

        ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),
                paUnanticipatedHostError );
        component->numBufs = bufInfo.fragstotal;

        /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */
        ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );

        component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;
        component->hostChannelCount = chans;
        component->hostFormat = hostFormat;
    }
    else
    {
        component->hostFormat = master->hostFormat;
        component->hostFrames = master->hostFrames;
        component->hostChannelCount = master->hostChannelCount;
        component->numBufs = master->numBufs;
    }

    PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),
            paInsufficientMemory );

error:
    return result;
}

static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )
{
    PaError result = paNoError;
    size_t len = *frames * PaOssStreamComponent_FrameSize( component );
    ssize_t bytesRead;

    ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );
    *frames = bytesRead / PaOssStreamComponent_FrameSize( component );
    /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */

error:
    return result;
}

static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )
{
    PaError result = paNoError;
    size_t len = *frames * PaOssStreamComponent_FrameSize( component );
    ssize_t bytesWritten;

    ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );
    *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );
    /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */

error:
    return result;
}

/** Configure the stream according to input/output parameters.
 *
 * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by
 * the user, if so we'll record the actual number of host channels and adapt later.
 */
static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,
        double *inputLatency, double *outputLatency )
{
    PaError result = paNoError;
    int duplex = stream->capture && stream->playback;
    unsigned long framesPerHostBuffer = 0;

    /* We should request full duplex first thing after opening the device */
    if( duplex && stream->sharedDevice )
        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );

    if( stream->capture )
    {
        PaOssStreamComponent *component = stream->capture;
        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In,
                    NULL ) );

        assert( component->hostChannelCount > 0 );
        assert( component->hostFrames > 0 );

        *inputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
    }
    if( stream->playback )
    {
        PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;
        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,
                    master ) );

        assert( component->hostChannelCount > 0 );
        assert( component->hostFrames > 0 );

        *outputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
    }

    if( duplex )
        framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );
    else if( stream->capture )
        framesPerHostBuffer = stream->capture->hostFrames;
    else if( stream->playback )
        framesPerHostBuffer = stream->playback->hostFrames;

    stream->framesPerHostBuffer = framesPerHostBuffer;
    stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate );    /* Period in usecs, rounded up */

    stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

error:
    return result;
}

/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */

/** Open a PA OSS stream.
 *
 * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the
 * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both
 * directions are the same device we will demand the same number of channels. The number of channels can range
 * from 1 to the maximum supported by the device.
 *
 * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback
 * must reflect this, in addition the host latency per device should approximate the corresponding
 * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that
 * both capture and playback can agree on (they can be different devices), the buffer processor can adapt
 * between host and user buffer size, but the ratio should preferably be integral.
 */
static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** s,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
                           unsigned long framesPerBuffer,
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData )
{
    PaError result = paNoError;
    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
    PaOssStream *stream = NULL;
    int inputChannelCount = 0, outputChannelCount = 0;
    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;
    const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
    int bpInitialized = 0;
    double inLatency = 0., outLatency = 0.;
    int i = 0;

    /* validate platform specific flags */
    if( (streamFlags & paPlatformSpecificFlags) != 0 )
        return paInvalidFlag; /* unexpected platform specific flag */

    if( inputParameters )
    {
        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */
        inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];
        PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );

        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;
    }
    if( outputParameters )
    {
        outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];
        PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );

        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;
    }

    /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same
     * device is opened for both directions
     */
    if( inputChannelCount > 0 && outputChannelCount > 0 )
    {
        if( inputParameters->device == outputParameters->device )
        {
            if( inputParameters->channelCount != outputParameters->channelCount )
                return paInvalidChannelCount;
        }
    }

    /* Round framesPerBuffer to the next power-of-two to make OSS happy. */
    if( framesPerBuffer != paFramesPerBufferUnspecified )
    {
        framesPerBuffer &= INT_MAX;
        for (i = 1; framesPerBuffer > i; i <<= 1) ;
        framesPerBuffer = i;
    }

    /* allocate and do basic initialization of the stream structure */
    PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
    PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );

    PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );

    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

    if( inputParameters )
    {
        inputHostFormat = stream->capture->hostFormat;
        stream->streamRepresentation.streamInfo.inputLatency = inLatency +
            PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
    }
    if( outputParameters )
    {
        outputHostFormat = stream->playback->hostFormat;
        stream->streamRepresentation.streamInfo.outputLatency = outLatency +
            PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
    }

    /* Initialize buffer processor with fixed host buffer size.
     * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will
     * convert between the two.
     */
    PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
              inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,
              outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,
              paUtilFixedHostBufferSize, streamCallback, userData ) );
    bpInitialized = 1;

    *s = (PaStream*)stream;

    return result;

error:
    if( bpInitialized )
        PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
    if( stream )
        PaOssStream_Terminate( stream );

    return result;
}

/*! Poll on I/O filedescriptors.

  Poll till we've determined there's data for read or write. In the full-duplex case,
  we don't want to hang around forever waiting for either input or output frames, so
  whenever we have a timed out filedescriptor we check if we're nearing under/overrun
  for the other direction (critical limit set at one buffer). If so, we exit the waiting
  state, and go on with what we got. We align the number of frames on a host buffer
  boundary because it is possible that the buffer size differs for the two directions and
  the host buffer size is a compromise between the two.
  */
static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )
{
    PaError result = paNoError;
    int pollPlayback = 0, pollCapture = 0;
    int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;
    audio_buf_info bufInfo;
    /* int ofs = 0, nfds = stream->nfds; */
    fd_set readFds, writeFds;
    int nfds = 0;
    struct timeval selectTimeval = {0, 0};
    unsigned long timeout = stream->pollTimeout;    /* In usecs */
    int captureFd = -1, playbackFd = -1;

    assert( stream );
    assert( frames );

    if( stream->capture )
    {
        pollCapture = 1;
        captureFd = stream->capture->fd;
        /* stream->capture->pfd->events = POLLIN; */
    }
    if( stream->playback )
    {
        pollPlayback = 1;
        playbackFd = stream->playback->fd;
        /* stream->playback->pfd->events = POLLOUT; */
    }

    FD_ZERO( &readFds );
    FD_ZERO( &writeFds );

    while( pollPlayback || pollCapture )
    {
#ifdef PTHREAD_CANCELED
        pthread_testcancel();
#else
        /* avoid indefinite waiting on thread not supporting cancellation */
        if( stream->callbackStop || stream->callbackAbort )
        {
            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
            (*frames) = 0;
            return paNoError;
        }
#endif

        /* select may modify the timeout parameter */
        selectTimeval.tv_usec = timeout;
        nfds = 0;

        if( pollCapture )
        {
            FD_SET( captureFd, &readFds );
            nfds = captureFd + 1;
        }
        if( pollPlayback )
        {
            FD_SET( playbackFd, &writeFds );
            nfds = PA_MAX( nfds, playbackFd + 1 );
        }
        ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );
        /*
        if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )
        {

            ENSURE_( -1, paUnanticipatedHostError );
        }
        */
#ifdef PTHREAD_CANCELED
        pthread_testcancel();
#else
        /* avoid indefinite waiting on thread not supporting cancellation */
        if( stream->callbackStop || stream->callbackAbort )
        {
            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
            (*frames) = 0;
            return paNoError;
        }
#endif
        if( pollCapture )
        {
            if( FD_ISSET( captureFd, &readFds ) )
            {
                FD_CLR( captureFd, &readFds );
                pollCapture = 0;
            }
            /*
            if( stream->capture->pfd->revents & POLLIN )
            {
                --nfds;
                ++ofs;
                pollCapture = 0;
            }
            */
            else if( stream->playback ) /* Timed out, go on with playback? */
            {
                /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",
                            __FUNCTION__, stream->pollTimeout ));*/
            }
        }
        if( pollPlayback )
        {
            if( FD_ISSET( playbackFd, &writeFds ) )
            {
                FD_CLR( playbackFd, &writeFds );
                pollPlayback = 0;
            }
            /*
            if( stream->playback->pfd->revents & POLLOUT )
            {
                --nfds;
                pollPlayback = 0;
            }
            */
            else if( stream->capture )  /* Timed out, go on with capture? */
            {
                /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",
                            __FUNCTION__, stream->pollTimeout ));*/
            }
        }
    }

    if( stream->capture )
    {
        ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );
        captureAvail = bufInfo.fragments * stream->capture->hostFrames;
        if( !captureAvail )
            PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));

        captureAvail = captureAvail == 0 ? INT_MAX : captureAvail;      /* Disregard if zero */
    }
    if( stream->playback )
    {
        ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );
        playbackAvail = bufInfo.fragments * stream->playback->hostFrames;
        if( !playbackAvail )
        {
            PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));
        }

        playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail;      /* Disregard if zero */
    }

    commonAvail = PA_MIN( captureAvail, playbackAvail );
    if( commonAvail == INT_MAX )
        commonAvail = 0;
    commonAvail -= commonAvail % stream->framesPerHostBuffer;

    assert( commonAvail != INT_MAX );
    assert( commonAvail >= 0 );
    *frames = commonAvail;

error:
    return result;
}

/** Prepare stream for capture/playback.
 *
 * In order to synchronize capture and playback properly we use the SETTRIGGER command.
 */
static PaError PaOssStream_Prepare( PaOssStream *stream )
{
    PaError result = paNoError;
    int enableBits = 0;

    if( stream->triggered )
        return result;

    /* The OSS reference instructs us to clear direction bits before setting them.*/
    if( stream->playback )
        ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
    if( stream->capture )
        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

    if( stream->playback )
    {
        size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
        memset( stream->playback->buffer, 0, bufSz );

        /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer
         * OSS will complain. */
        PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
        while (1)
        {
            if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )
                break;
        }
        PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );
    }

    if( stream->sharedDevice )
    {
        enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
    }
    else
    {
        if( stream->capture )
        {
            enableBits = PCM_ENABLE_INPUT;
            ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
        }
        if( stream->playback )
        {
            enableBits = PCM_ENABLE_OUTPUT;
            ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
        }
    }

    /* Ok, we have triggered the stream */
    stream->triggered = 1;

error:
    return result;
}

/** Stop audio processing
 *
 */
static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
{
    PaError result = paNoError;

    /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
     * Also disable capture/playback till the stream is started again.
     */
    int captureErr = 0, playbackErr = 0;
    if( stream->capture )
    {
        if( (captureErr = ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 )) < 0 )
        {
            PA_DEBUG(( "%s: Failed to stop capture device, error: %d\n", __FUNCTION__, captureErr ));
        }
    }
    if( stream->playback && !stream->sharedDevice )
    {
        if( (playbackErr = ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 )) < 0 )
        {
            PA_DEBUG(( "%s: Failed to stop playback device, error: %d\n", __FUNCTION__, playbackErr ));
        }
    }

    if( captureErr || playbackErr )
    {
        result = paUnanticipatedHostError;
    }

    return result;
}

/** Clean up after thread exit.
 *
 * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here
 */
static void OnExit( void *data )
{
    PaOssStream *stream = (PaOssStream *) data;
    assert( data );

    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );

    PaOssStream_Stop( stream, stream->callbackAbort );

    PA_DEBUG(( "OnExit: Stoppage\n" ));

    /* Eventually notify user all buffers have played */
    if( stream->streamRepresentation.streamFinishedCallback )
        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

    stream->callbackAbort = 0;      /* Clear state */
    stream->isActive = 0;
}

static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )
{
    PaError result = paNoError;

    if( stream->capture )
    {
        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,
                stream->capture->hostChannelCount );
        PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );
    }
    if( stream->playback )
    {
        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,
                stream->playback->hostChannelCount );
        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );
    }

    return result;
}

/** Thread procedure for callback processing.
 *
 * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the
 * callback should be used for buffer priming. When the stream is cancelled a separate function will
 * take care of the transition to the Callback Finished state (the stream isn't considered Stopped
 * before StopStream() or AbortStream() are called).
 */
static void *PaOSS_AudioThreadProc( void *userData )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)userData;
    unsigned long framesAvail = 0, framesProcessed = 0;
    int callbackResult = paContinue;
    int triggered = stream->triggered;  /* See if SNDCTL_DSP_TRIGGER has been issued already */
    int initiateProcessing = triggered;    /* Already triggered? */
    PaStreamCallbackFlags cbFlags = 0;  /* We might want to keep state across iterations */
    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */

    /*
#if ( SOUND_VERSION > 0x030904 )
        audio_errinfo errinfo;
#endif
*/

    assert( stream );

    pthread_cleanup_push( &OnExit, stream );    /* Execute OnExit when exiting */

    /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and
     * playback in sync, when the stream is restarted after being stopped we simply start by reading/
     * writing.
     */
    PA_ENSURE( PaOssStream_Prepare( stream ) );

    /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */
    if( initiateProcessing )
    {
        /* Make sure devices are in blocking mode */
        if( stream->capture )
            ModifyBlocking( stream->capture->fd, 1 );
        if( stream->playback )
            ModifyBlocking( stream->playback->fd, 1 );
    }

    while( 1 )
    {
#ifdef PTHREAD_CANCELED
        pthread_testcancel();
#else
        if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancellation */
        {
            PA_DEBUG(( "Aborting callback thread\n" ));
            break;
        }
#endif
        if( stream->callbackStop && callbackResult == paContinue )
        {
            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
            callbackResult = paComplete;
        }

        /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless
         * the stream has been recently started, we will have to go right ahead and read/write in blocking
         * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch
         * to non-blocking mode.
         */
        if( !initiateProcessing )
        {
            /* Wait on available frames */
            PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) );
            assert( framesAvail % stream->framesPerHostBuffer == 0 );
        }
        else
        {
            framesAvail = stream->framesPerHostBuffer;
        }

        while( framesAvail > 0 )
        {
            unsigned long frames = framesAvail;

#ifdef PTHREAD_CANCELED
            pthread_testcancel();
#else
            if( stream->callbackStop )
            {
                PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
                callbackResult = paComplete;
            }

            if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancellation */
            {
                PA_DEBUG(( "Aborting callback thread\n" ));
                break;
            }
#endif
            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

            /* Read data */
            if ( stream->capture )
            {
                PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );
                if( frames < framesAvail )
                {
                    PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames ));
                    framesAvail = frames;
                }
            }

#if ( SOUND_VERSION >= 0x030904 )
            /*
               Check with OSS to see if there have been any under/overruns
               since last time we checked.
               */
            /*
            if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )
            {
                if( errinfo.play_underruns )
                    cbFlags |= paOutputUnderflow ;
                if( errinfo.record_underruns )
                    cbFlags |= paInputUnderflow ;
            }
            else
                PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));
                */
#endif

            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
                    cbFlags );
            cbFlags = 0;
            PA_ENSURE( SetUpBuffers( stream, framesAvail ) );

            framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
                    &callbackResult );
            assert( framesProcessed == framesAvail );
            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );

            if ( stream->playback )
            {
                frames = framesAvail;

                PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );
                if( frames < framesAvail )
                {
                    /* TODO: handle bytesWritten != bytesRequested (slippage?) */
                    PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames ));
                }
            }

            framesAvail -= framesProcessed;
            stream->framesProcessed += framesProcessed;

            if( callbackResult != paContinue )
                break;
        }

        if( initiateProcessing || !triggered )
        {
            /* Non-blocking */
            if( stream->capture )
                PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );
            if( stream->playback && !stream->sharedDevice )
                PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );

            initiateProcessing = 0;
            sem_post( &stream->semaphore );
        }

        if( callbackResult != paContinue )
        {
            stream->callbackAbort = callbackResult == paAbort;
            if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
                break;
        }
    }

    pthread_cleanup_pop( 1 );

error:
    pthread_exit( NULL );
}

/** Close the stream.
 *
 */
static PaError CloseStream( PaStream* s )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;

    assert( stream );

    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
    PaOssStream_Terminate( stream );

    return result;
}

/** Start the stream.
 *
 * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual
 * callback will be repeatedly called in a separate thread. If a separate thread is started this function
 * will block until it has started processing audio, otherwise audio processing is started directly.
 */
static PaError StartStream( PaStream *s )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;

    stream->isActive = 1;
    stream->isStopped = 0;
    stream->lastPosPtr = 0;
    stream->lastStreamBytes = 0;
    stream->framesProcessed = 0;

    /* only use the thread for callback streams */
    if( stream->bufferProcessor.streamCallback )
    {
        PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );
        sem_wait( &stream->semaphore );
    }
    else
        PA_ENSURE( PaOssStream_Prepare( stream ) );

error:
    return result;
}

static PaError RealStop( PaOssStream *stream, int abort )
{
    PaError result = paNoError;

    if( stream->callbackMode )
    {
        if( abort )
            stream->callbackAbort = 1;
        else
            stream->callbackStop = 1;

        PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );

        stream->callbackStop = stream->callbackAbort = 0;
    }
    else
        PA_ENSURE( PaOssStream_Stop( stream, abort ) );

    stream->isStopped = 1;

error:
    return result;
}

/** Stop the stream.
 *
 * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued
 * buffers.
 */
static PaError StopStream( PaStream *s )
{
    return RealStop( (PaOssStream *)s, 0 );
}

/** Abort the stream.
 *
 * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued
 * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing
 * the OSS device.
 */
static PaError AbortStream( PaStream *s )
{
    return RealStop( (PaOssStream *)s, 1 );
}

/** Is the stream in the Stopped state.
 *
 */
static PaError IsStreamStopped( PaStream *s )
{
    PaOssStream *stream = (PaOssStream*)s;

    return (stream->isStopped);
}

/** Is the stream in the Active state.
 *
 */
static PaError IsStreamActive( PaStream *s )
{
    PaOssStream *stream = (PaOssStream*)s;

    return (stream->isActive);
}

static PaTime GetStreamTime( PaStream *s )
{
    PaOssStream *stream = (PaOssStream*)s;
    count_info info;
    int delta;

    if( stream->playback ) {
        if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {
            delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;
            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;
        }
    }
    else {
        if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {
            delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;
            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;
        }
    }

    /* the ioctl failed, but we can still give a coarse estimate */

    return stream->framesProcessed / stream->sampleRate;
}


static double GetStreamCpuLoad( PaStream* s )
{
    PaOssStream *stream = (PaOssStream*)s;

    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
}


/*
    As separate stream interfaces are used for blocking and callback
    streams, the following functions can be guaranteed to only be called
    for blocking streams.
*/


static PaError ReadStream( PaStream* s,
                           void *buffer,
                           unsigned long frames )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;
    int bytesRequested, bytesRead;
    unsigned long framesRequested;
    void *userBuffer;

    /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,
     * so we copy the user provided pointers */
    if( stream->bufferProcessor.userInputIsInterleaved )
        userBuffer = buffer;
    else /* Copy channels into local array */
    {
        userBuffer = stream->capture->userBuffers;
        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );
    }

    while( frames )
    {
        framesRequested = PA_MIN( frames, stream->capture->hostFrames );

        bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
        ENSURE_( (bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested )),
                    paUnanticipatedHostError );
        if ( bytesRequested != bytesRead )
        {
            PA_DEBUG(( "Requested %d bytes, read %d\n", bytesRequested, bytesRead ));
            return paUnanticipatedHostError;
        }

        PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
        PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
        frames -= framesRequested;
    }

error:
    return result;
}


static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;
    int bytesRequested, bytesWritten;
    unsigned long framesConverted;
    const void *userBuffer;

    /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,
     * so we copy the user provided pointers */
    if( stream->bufferProcessor.userOutputIsInterleaved )
        userBuffer = buffer;
    else
    {
        /* Copy channels into local array */
        userBuffer = stream->playback->userBuffers;
        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );
    }

    while( frames )
    {
        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );
        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );

        framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );
        frames -= framesConverted;

        bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
        ENSURE_( (bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested )),
                    paUnanticipatedHostError );

        if ( bytesRequested != bytesWritten )
        {
            PA_DEBUG(( "Requested %d bytes, wrote %d\n", bytesRequested, bytesWritten ));
            return paUnanticipatedHostError;
        }
    }

error:
    return result;
}


static signed long GetStreamReadAvailable( PaStream* s )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;
    audio_buf_info info;

    ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ), paUnanticipatedHostError );
    return info.fragments * stream->capture->hostFrames;

error:
    return result;
}


/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
static signed long GetStreamWriteAvailable( PaStream* s )
{
    PaError result = paNoError;
    PaOssStream *stream = (PaOssStream*)s;
    int delay = 0;
#ifdef SNDCTL_DSP_GETODELAY
    ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ), paUnanticipatedHostError );
#endif
    return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );

/* Conditionally compile this to avoid warning about unused label */
#ifdef SNDCTL_DSP_GETODELAY
error:
    return result;
#endif
}