pa_unix_oss.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046
  1. /*
  2. * $Id: pa_unix_oss.c 1894 2013-06-08 19:30:41Z gineera $
  3. * PortAudio Portable Real-Time Audio Library
  4. * Latest Version at: http://www.portaudio.com
  5. * OSS implementation by:
  6. * Douglas Repetto
  7. * Phil Burk
  8. * Dominic Mazzoni
  9. * Arve Knudsen
  10. *
  11. * Based on the Open Source API proposed by Ross Bencina
  12. * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining
  15. * a copy of this software and associated documentation files
  16. * (the "Software"), to deal in the Software without restriction,
  17. * including without limitation the rights to use, copy, modify, merge,
  18. * publish, distribute, sublicense, and/or sell copies of the Software,
  19. * and to permit persons to whom the Software is furnished to do so,
  20. * subject to the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be
  23. * included in all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  28. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  29. * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  30. * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. /*
  34. * The text above constitutes the entire PortAudio license; however,
  35. * the PortAudio community also makes the following non-binding requests:
  36. *
  37. * Any person wishing to distribute modifications to the Software is
  38. * requested to send the modifications to the original developer so that
  39. * they can be incorporated into the canonical version. It is also
  40. * requested that these non-binding requests be included along with the
  41. * license above.
  42. */
  43. /**
  44. @file
  45. @ingroup hostapi_src
  46. */
  47. #include <stdio.h>
  48. #include <string.h>
  49. #include <math.h>
  50. #include <fcntl.h>
  51. #include <sys/ioctl.h>
  52. #include <unistd.h>
  53. #include <pthread.h>
  54. #include <stdlib.h>
  55. #include <assert.h>
  56. #include <errno.h>
  57. #include <sys/types.h>
  58. #include <sys/stat.h>
  59. #include <sys/poll.h>
  60. #include <limits.h>
  61. #include <semaphore.h>
  62. #ifdef HAVE_SYS_SOUNDCARD_H
  63. # include <sys/soundcard.h>
  64. # ifdef __NetBSD__
  65. # define DEVICE_NAME_BASE "/dev/audio"
  66. # else
  67. # define DEVICE_NAME_BASE "/dev/dsp"
  68. # endif
  69. #elif defined(HAVE_LINUX_SOUNDCARD_H)
  70. # include <linux/soundcard.h>
  71. # define DEVICE_NAME_BASE "/dev/dsp"
  72. #elif defined(HAVE_MACHINE_SOUNDCARD_H)
  73. # include <machine/soundcard.h> /* JH20010905 */
  74. # define DEVICE_NAME_BASE "/dev/audio"
  75. #else
  76. # error No sound card header file
  77. #endif
  78. #include "portaudio.h"
  79. #include "pa_util.h"
  80. #include "pa_allocation.h"
  81. #include "pa_hostapi.h"
  82. #include "pa_stream.h"
  83. #include "pa_cpuload.h"
  84. #include "pa_process.h"
  85. #include "pa_unix_util.h"
  86. #include "pa_debugprint.h"
  87. static int sysErr_;
  88. static pthread_t mainThread_;
  89. /* Check return value of system call, and map it to PaError */
  90. #define ENSURE_(expr, code) \
  91. do { \
  92. if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \
  93. { \
  94. /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
  95. if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
  96. { \
  97. PaUtil_SetLastHostErrorInfo( paOSS, sysErr_, strerror( errno ) ); \
  98. } \
  99. \
  100. PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
  101. result = (code); \
  102. goto error; \
  103. } \
  104. } while( 0 );
  105. #ifndef AFMT_S16_NE
  106. #define AFMT_S16_NE Get_AFMT_S16_NE()
  107. /*********************************************************************
  108. * Some versions of OSS do not define AFMT_S16_NE. So check CPU.
  109. * PowerPC is Big Endian. X86 is Little Endian.
  110. */
  111. static int Get_AFMT_S16_NE( void )
  112. {
  113. long testData = 1;
  114. char *ptr = (char *) &testData;
  115. int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */
  116. return isLittle ? AFMT_S16_LE : AFMT_S16_BE;
  117. }
  118. #endif
  119. /* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */
  120. typedef struct
  121. {
  122. PaUtilHostApiRepresentation inheritedHostApiRep;
  123. PaUtilStreamInterface callbackStreamInterface;
  124. PaUtilStreamInterface blockingStreamInterface;
  125. PaUtilAllocationGroup *allocations;
  126. PaHostApiIndex hostApiIndex;
  127. }
  128. PaOSSHostApiRepresentation;
  129. /** Per-direction structure for PaOssStream.
  130. *
  131. * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,
  132. * but with different number of channels we will have to adapt between the number of user and host
  133. * channels for at least one direction, since the configuration space is the same for both directions
  134. * of an OSS device.
  135. */
  136. typedef struct
  137. {
  138. int fd;
  139. const char *devName;
  140. int userChannelCount, hostChannelCount;
  141. int userInterleaved;
  142. void *buffer;
  143. PaSampleFormat userFormat, hostFormat;
  144. double latency;
  145. unsigned long hostFrames, numBufs;
  146. void **userBuffers; /* For non-interleaved blocking */
  147. } PaOssStreamComponent;
  148. /** Implementation specific representation of a PaStream.
  149. *
  150. */
  151. typedef struct PaOssStream
  152. {
  153. PaUtilStreamRepresentation streamRepresentation;
  154. PaUtilCpuLoadMeasurer cpuLoadMeasurer;
  155. PaUtilBufferProcessor bufferProcessor;
  156. PaUtilThreading threading;
  157. int sharedDevice;
  158. unsigned long framesPerHostBuffer;
  159. int triggered; /* Have the devices been triggered yet (first start) */
  160. int isActive;
  161. int isStopped;
  162. int lastPosPtr;
  163. double lastStreamBytes;
  164. int framesProcessed;
  165. double sampleRate;
  166. int callbackMode;
  167. volatile int callbackStop, callbackAbort;
  168. PaOssStreamComponent *capture, *playback;
  169. unsigned long pollTimeout;
  170. sem_t semaphore;
  171. }
  172. PaOssStream;
  173. typedef enum {
  174. StreamMode_In,
  175. StreamMode_Out
  176. } StreamMode;
  177. /* prototypes for functions declared in this file */
  178. static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
  179. static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
  180. const PaStreamParameters *inputParameters,
  181. const PaStreamParameters *outputParameters,
  182. double sampleRate );
  183. static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
  184. PaStream** s,
  185. const PaStreamParameters *inputParameters,
  186. const PaStreamParameters *outputParameters,
  187. double sampleRate,
  188. unsigned long framesPerBuffer,
  189. PaStreamFlags streamFlags,
  190. PaStreamCallback *streamCallback,
  191. void *userData );
  192. static PaError CloseStream( PaStream* stream );
  193. static PaError StartStream( PaStream *stream );
  194. static PaError StopStream( PaStream *stream );
  195. static PaError AbortStream( PaStream *stream );
  196. static PaError IsStreamStopped( PaStream *s );
  197. static PaError IsStreamActive( PaStream *stream );
  198. static PaTime GetStreamTime( PaStream *stream );
  199. static double GetStreamCpuLoad( PaStream* stream );
  200. static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
  201. static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
  202. static signed long GetStreamReadAvailable( PaStream* stream );
  203. static signed long GetStreamWriteAvailable( PaStream* stream );
  204. static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );
  205. /** Initialize the OSS API implementation.
  206. *
  207. * This function will initialize host API datastructures and query host devices for information.
  208. *
  209. * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here
  210. *
  211. * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,
  212. * this happens with the usual "error" label.
  213. */
  214. PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
  215. {
  216. PaError result = paNoError;
  217. PaOSSHostApiRepresentation *ossHostApi = NULL;
  218. PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),
  219. paInsufficientMemory );
  220. PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
  221. ossHostApi->hostApiIndex = hostApiIndex;
  222. /* Initialize host API structure */
  223. *hostApi = &ossHostApi->inheritedHostApiRep;
  224. (*hostApi)->info.structVersion = 1;
  225. (*hostApi)->info.type = paOSS;
  226. (*hostApi)->info.name = "OSS";
  227. (*hostApi)->Terminate = Terminate;
  228. (*hostApi)->OpenStream = OpenStream;
  229. (*hostApi)->IsFormatSupported = IsFormatSupported;
  230. PA_ENSURE( BuildDeviceList( ossHostApi ) );
  231. PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,
  232. StopStream, AbortStream, IsStreamStopped, IsStreamActive,
  233. GetStreamTime, GetStreamCpuLoad,
  234. PaUtil_DummyRead, PaUtil_DummyWrite,
  235. PaUtil_DummyGetReadAvailable,
  236. PaUtil_DummyGetWriteAvailable );
  237. PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,
  238. StopStream, AbortStream, IsStreamStopped, IsStreamActive,
  239. GetStreamTime, PaUtil_DummyGetCpuLoad,
  240. ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
  241. mainThread_ = pthread_self();
  242. return result;
  243. error:
  244. if( ossHostApi )
  245. {
  246. if( ossHostApi->allocations )
  247. {
  248. PaUtil_FreeAllAllocations( ossHostApi->allocations );
  249. PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
  250. }
  251. PaUtil_FreeMemory( ossHostApi );
  252. }
  253. return result;
  254. }
  255. PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,
  256. int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,
  257. PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations )
  258. {
  259. PaError result = paNoError;
  260. deviceInfo->structVersion = 2;
  261. if( allocations )
  262. {
  263. size_t len = strlen( name ) + 1;
  264. PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );
  265. strncpy( (char *)deviceInfo->name, name, len );
  266. }
  267. else
  268. deviceInfo->name = name;
  269. deviceInfo->hostApi = hostApiIndex;
  270. deviceInfo->maxInputChannels = maxInputChannels;
  271. deviceInfo->maxOutputChannels = maxOutputChannels;
  272. deviceInfo->defaultLowInputLatency = defaultLowInputLatency;
  273. deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;
  274. deviceInfo->defaultHighInputLatency = defaultHighInputLatency;
  275. deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;
  276. deviceInfo->defaultSampleRate = defaultSampleRate;
  277. error:
  278. return result;
  279. }
  280. static int CalcHigherLogTwo( int n )
  281. {
  282. int log2 = 0;
  283. while( (1<<log2) < n ) log2++;
  284. return log2;
  285. }
  286. static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,
  287. double *defaultLowLatency, double *defaultHighLatency )
  288. {
  289. PaError result = paNoError;
  290. int numChannels, maxNumChannels;
  291. int busy = 0;
  292. int devHandle = -1;
  293. int sr;
  294. *maxChannelCount = 0; /* Default value in case this fails */
  295. int temp, frgmt;
  296. unsigned long fragFrames;
  297. if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK )) < 0 )
  298. {
  299. if( errno == EBUSY || errno == EAGAIN )
  300. {
  301. PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));
  302. }
  303. else
  304. {
  305. /* Ignore ENOENT, which means we've tried a non-existent device */
  306. if( errno != ENOENT )
  307. {
  308. PA_DEBUG(( "%s: Can't access device %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
  309. }
  310. }
  311. return paDeviceUnavailable;
  312. }
  313. /* Negotiate for the maximum number of channels for this device. PLB20010927
  314. * Consider up to 16 as the upper number of channels.
  315. * Variable maxNumChannels should contain the actual upper limit after the call.
  316. * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
  317. */
  318. maxNumChannels = 0;
  319. for( numChannels = 1; numChannels <= 16; numChannels++ )
  320. {
  321. temp = numChannels;
  322. if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )
  323. {
  324. busy = EAGAIN == errno || EBUSY == errno;
  325. /* ioctl() failed so bail out if we already have stereo */
  326. if( maxNumChannels >= 2 )
  327. break;
  328. }
  329. else
  330. {
  331. /* ioctl() worked but bail out if it does not support numChannels.
  332. * We don't want to leave gaps in the numChannels supported.
  333. */
  334. if( (numChannels > 2) && (temp != numChannels) )
  335. break;
  336. if( temp > maxNumChannels )
  337. maxNumChannels = temp; /* Save maximum. */
  338. }
  339. }
  340. /* A: We're able to open a device for capture if it's busy playing back and vice versa,
  341. * but we can't configure anything */
  342. if( 0 == maxNumChannels && busy )
  343. {
  344. result = paDeviceUnavailable;
  345. goto error;
  346. }
  347. /* The above negotiation may fail for an old driver so try this older technique. */
  348. if( maxNumChannels < 1 )
  349. {
  350. int stereo = 1;
  351. if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )
  352. {
  353. maxNumChannels = 1;
  354. }
  355. else
  356. {
  357. maxNumChannels = (stereo) ? 2 : 1;
  358. }
  359. PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ));
  360. }
  361. /* During channel negotiation, the last ioctl() may have failed. This can
  362. * also cause sample rate negotiation to fail. Hence the following, to return
  363. * to a supported number of channels. SG20011005 */
  364. {
  365. /* use most reasonable default value */
  366. numChannels = PA_MIN( maxNumChannels, 2 );
  367. ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &numChannels ), paUnanticipatedHostError );
  368. }
  369. /* Get supported sample rate closest to 44100 Hz */
  370. if( *defaultSampleRate < 0 )
  371. {
  372. sr = 44100;
  373. ENSURE_( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ), paUnanticipatedHostError );
  374. *defaultSampleRate = sr;
  375. }
  376. *maxChannelCount = maxNumChannels;
  377. /* Attempt to set low latency with 4 frags-per-buffer, 128 frames-per-frag (total buffer 512 frames)
  378. * since the ioctl sets bytes, multiply by numChannels, and base on 2 bytes-per-sample, */
  379. fragFrames = 128;
  380. frgmt = (4 << 16) + (CalcHigherLogTwo( fragFrames * numChannels * 2 ) & 0xffff);
  381. ENSURE_( ioctl( devHandle, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
  382. /* Use the value set by the ioctl to give the latency achieved */
  383. fragFrames = pow( 2, frgmt & 0xffff ) / (numChannels * 2);
  384. *defaultLowLatency = ((frgmt >> 16) - 1) * fragFrames / *defaultSampleRate;
  385. /* Cannot now try setting a high latency (device would need closing and opening again). Make
  386. * high-latency 4 times the low unless the fragFrames are significantly more than requested 128 */
  387. temp = (fragFrames < 256) ? 4 : (fragFrames < 512) ? 2 : 1;
  388. *defaultHighLatency = temp * *defaultLowLatency;
  389. error:
  390. if( devHandle >= 0 )
  391. close( devHandle );
  392. return result;
  393. }
  394. /** Query OSS device.
  395. *
  396. * This is where PaDeviceInfo objects are constructed and filled in with relevant information.
  397. *
  398. * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed
  399. * in place.
  400. */
  401. static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )
  402. {
  403. PaError result = paNoError;
  404. double sampleRate = -1.;
  405. int maxInputChannels, maxOutputChannels;
  406. PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;
  407. PaError tmpRes = paNoError;
  408. int busy = 0;
  409. *deviceInfo = NULL;
  410. /* douglas:
  411. we have to do this querying in a slightly different order. apparently
  412. some sound cards will give you different info based on their settins.
  413. e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
  414. the correct order for OSS is: format, channels, sample rate
  415. */
  416. /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is
  417. * opened in, it may have more channels available for capture than playback and vice versa. Therefore
  418. * we will open the device in both read- and write-only mode to determine the supported number.
  419. */
  420. if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,
  421. &defaultHighInputLatency )) != paNoError )
  422. {
  423. if( tmpRes != paDeviceUnavailable )
  424. {
  425. PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));
  426. /* PA_ENSURE( tmpRes ); */
  427. }
  428. ++busy;
  429. }
  430. if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,
  431. &defaultHighOutputLatency )) != paNoError )
  432. {
  433. if( tmpRes != paDeviceUnavailable )
  434. {
  435. PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));
  436. /* PA_ENSURE( tmpRes ); */
  437. }
  438. ++busy;
  439. }
  440. assert( 0 <= busy && busy <= 2 );
  441. if( 2 == busy ) /* Both directions are unavailable to us */
  442. {
  443. result = paDeviceUnavailable;
  444. goto error;
  445. }
  446. PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );
  447. PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,
  448. defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,
  449. ossApi->allocations ) );
  450. error:
  451. return result;
  452. }
  453. /** Query host devices.
  454. *
  455. * Loop over host devices and query their capabilitiesu
  456. *
  457. * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object
  458. * per device, these are placed in the host api representation's deviceInfos array.
  459. */
  460. static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
  461. {
  462. PaError result = paNoError;
  463. PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;
  464. int i;
  465. int numDevices = 0, maxDeviceInfos = 1;
  466. PaDeviceInfo **deviceInfos = NULL;
  467. /* These two will be set to the first working input and output device, respectively */
  468. commonApi->info.defaultInputDevice = paNoDevice;
  469. commonApi->info.defaultOutputDevice = paNoDevice;
  470. /* Find devices by calling QueryDevice on each
  471. * potential device names. When we find a valid one,
  472. * add it to a linked list.
  473. * A: Set an arbitrary of 100 devices, should probably be a smarter way. */
  474. for( i = 0; i < 100; i++ )
  475. {
  476. char deviceName[32];
  477. PaDeviceInfo *deviceInfo;
  478. int testResult;
  479. if( i == 0 )
  480. snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
  481. else
  482. snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);
  483. /* PA_DEBUG(("%s: trying device %s\n", __FUNCTION__, deviceName )); */
  484. if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
  485. {
  486. if( testResult != paDeviceUnavailable )
  487. PA_ENSURE( testResult );
  488. continue;
  489. }
  490. ++numDevices;
  491. if( !deviceInfos || numDevices > maxDeviceInfos )
  492. {
  493. maxDeviceInfos *= 2;
  494. PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),
  495. paInsufficientMemory );
  496. }
  497. {
  498. int devIdx = numDevices - 1;
  499. deviceInfos[devIdx] = deviceInfo;
  500. if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )
  501. commonApi->info.defaultInputDevice = devIdx;
  502. if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )
  503. commonApi->info.defaultOutputDevice = devIdx;
  504. }
  505. }
  506. /* Make an array of PaDeviceInfo pointers out of the linked list */
  507. PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));
  508. commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
  509. ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
  510. memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );
  511. commonApi->info.deviceCount = numDevices;
  512. error:
  513. free( deviceInfos );
  514. return result;
  515. }
  516. static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
  517. {
  518. PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
  519. if( ossHostApi->allocations )
  520. {
  521. PaUtil_FreeAllAllocations( ossHostApi->allocations );
  522. PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
  523. }
  524. PaUtil_FreeMemory( ossHostApi );
  525. }
  526. static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
  527. const PaStreamParameters *inputParameters,
  528. const PaStreamParameters *outputParameters,
  529. double sampleRate )
  530. {
  531. PaError result = paNoError;
  532. PaDeviceIndex device;
  533. PaDeviceInfo *deviceInfo;
  534. char *deviceName;
  535. int inputChannelCount, outputChannelCount;
  536. int tempDevHandle = -1;
  537. int flags;
  538. PaSampleFormat inputSampleFormat, outputSampleFormat;
  539. if( inputParameters )
  540. {
  541. inputChannelCount = inputParameters->channelCount;
  542. inputSampleFormat = inputParameters->sampleFormat;
  543. /* unless alternate device specification is supported, reject the use of
  544. paUseHostApiSpecificDeviceSpecification */
  545. if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
  546. return paInvalidDevice;
  547. /* check that input device can support inputChannelCount */
  548. if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
  549. return paInvalidChannelCount;
  550. /* validate inputStreamInfo */
  551. if( inputParameters->hostApiSpecificStreamInfo )
  552. return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
  553. }
  554. else
  555. {
  556. inputChannelCount = 0;
  557. }
  558. if( outputParameters )
  559. {
  560. outputChannelCount = outputParameters->channelCount;
  561. outputSampleFormat = outputParameters->sampleFormat;
  562. /* unless alternate device specification is supported, reject the use of
  563. paUseHostApiSpecificDeviceSpecification */
  564. if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
  565. return paInvalidDevice;
  566. /* check that output device can support inputChannelCount */
  567. if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
  568. return paInvalidChannelCount;
  569. /* validate outputStreamInfo */
  570. if( outputParameters->hostApiSpecificStreamInfo )
  571. return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
  572. }
  573. else
  574. {
  575. outputChannelCount = 0;
  576. }
  577. if (inputChannelCount == 0 && outputChannelCount == 0)
  578. return paInvalidChannelCount;
  579. /* if full duplex, make sure that they're the same device */
  580. if (inputChannelCount > 0 && outputChannelCount > 0 &&
  581. inputParameters->device != outputParameters->device)
  582. return paInvalidDevice;
  583. /* if full duplex, also make sure that they're the same number of channels */
  584. if (inputChannelCount > 0 && outputChannelCount > 0 &&
  585. inputChannelCount != outputChannelCount)
  586. return paInvalidChannelCount;
  587. /* open the device so we can do more tests */
  588. if( inputChannelCount > 0 )
  589. {
  590. result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);
  591. if (result != paNoError)
  592. return result;
  593. }
  594. else
  595. {
  596. result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);
  597. if (result != paNoError)
  598. return result;
  599. }
  600. deviceInfo = hostApi->deviceInfos[device];
  601. deviceName = (char *)deviceInfo->name;
  602. flags = O_NONBLOCK;
  603. if (inputChannelCount > 0 && outputChannelCount > 0)
  604. flags |= O_RDWR;
  605. else if (inputChannelCount > 0)
  606. flags |= O_RDONLY;
  607. else
  608. flags |= O_WRONLY;
  609. ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );
  610. /* PaOssStream_Configure will do the rest of the checking for us */
  611. /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */
  612. /* everything succeeded! */
  613. error:
  614. if( tempDevHandle >= 0 )
  615. close( tempDevHandle );
  616. return result;
  617. }
  618. /** Validate stream parameters.
  619. *
  620. * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device
  621. */
  622. static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )
  623. {
  624. int maxChans;
  625. assert( parameters );
  626. if( parameters->device == paUseHostApiSpecificDeviceSpecification )
  627. {
  628. return paInvalidDevice;
  629. }
  630. maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels :
  631. deviceInfo->maxOutputChannels);
  632. if( parameters->channelCount > maxChans )
  633. {
  634. return paInvalidChannelCount;
  635. }
  636. return paNoError;
  637. }
  638. static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,
  639. int callbackMode, int fd, const char *deviceName )
  640. {
  641. PaError result = paNoError;
  642. assert( component );
  643. memset( component, 0, sizeof (PaOssStreamComponent) );
  644. component->fd = fd;
  645. component->devName = deviceName;
  646. component->userChannelCount = parameters->channelCount;
  647. component->userFormat = parameters->sampleFormat;
  648. component->latency = parameters->suggestedLatency;
  649. component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);
  650. if( !callbackMode && !component->userInterleaved )
  651. {
  652. /* Pre-allocate non-interleaved user provided buffers */
  653. PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),
  654. paInsufficientMemory );
  655. }
  656. error:
  657. return result;
  658. }
  659. static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )
  660. {
  661. assert( component );
  662. if( component->fd >= 0 )
  663. close( component->fd );
  664. if( component->buffer )
  665. PaUtil_FreeMemory( component->buffer );
  666. if( component->userBuffers )
  667. PaUtil_FreeMemory( component->userBuffers );
  668. PaUtil_FreeMemory( component );
  669. }
  670. static PaError ModifyBlocking( int fd, int blocking )
  671. {
  672. PaError result = paNoError;
  673. int fflags;
  674. ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );
  675. if( blocking )
  676. fflags &= ~O_NONBLOCK;
  677. else
  678. fflags |= O_NONBLOCK;
  679. ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );
  680. error:
  681. return result;
  682. }
  683. /** Open input and output devices.
  684. *
  685. * @param idev: Returned input device file descriptor.
  686. * @param odev: Returned output device file descriptor.
  687. */
  688. static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
  689. {
  690. PaError result = paNoError;
  691. int flags = O_NONBLOCK, duplex = 0;
  692. *idev = *odev = -1;
  693. if( idevName && odevName )
  694. {
  695. duplex = 1;
  696. flags |= O_RDWR;
  697. }
  698. else if( idevName )
  699. flags |= O_RDONLY;
  700. else
  701. flags |= O_WRONLY;
  702. /* open first in nonblocking mode, in case it's busy...
  703. * A: then unset the non-blocking attribute */
  704. assert( flags & O_NONBLOCK );
  705. if( idevName )
  706. {
  707. ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
  708. PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
  709. }
  710. if( odevName )
  711. {
  712. if( !idevName )
  713. {
  714. ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
  715. PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
  716. }
  717. else
  718. {
  719. ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );
  720. }
  721. }
  722. error:
  723. return result;
  724. }
  725. static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,
  726. PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,
  727. PaOSSHostApiRepresentation *ossApi )
  728. {
  729. PaError result = paNoError;
  730. int idev, odev;
  731. PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;
  732. const char *idevName = NULL, *odevName = NULL;
  733. assert( stream );
  734. memset( stream, 0, sizeof (PaOssStream) );
  735. stream->isStopped = 1;
  736. PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );
  737. if( inputParameters && outputParameters )
  738. {
  739. if( inputParameters->device == outputParameters->device )
  740. stream->sharedDevice = 1;
  741. }
  742. if( inputParameters )
  743. idevName = hostApi->deviceInfos[inputParameters->device]->name;
  744. if( outputParameters )
  745. odevName = hostApi->deviceInfos[outputParameters->device]->name;
  746. PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );
  747. if( inputParameters )
  748. {
  749. PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
  750. PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );
  751. }
  752. if( outputParameters )
  753. {
  754. PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
  755. PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );
  756. }
  757. if( callback != NULL )
  758. {
  759. PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
  760. &ossApi->callbackStreamInterface, callback, userData );
  761. stream->callbackMode = 1;
  762. }
  763. else
  764. {
  765. PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
  766. &ossApi->blockingStreamInterface, callback, userData );
  767. }
  768. ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );
  769. error:
  770. return result;
  771. }
  772. static void PaOssStream_Terminate( PaOssStream *stream )
  773. {
  774. assert( stream );
  775. PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
  776. PaUtil_TerminateThreading( &stream->threading );
  777. if( stream->capture )
  778. PaOssStreamComponent_Terminate( stream->capture );
  779. if( stream->playback )
  780. PaOssStreamComponent_Terminate( stream->playback );
  781. sem_destroy( &stream->semaphore );
  782. PaUtil_FreeMemory( stream );
  783. }
  784. /** Translate from PA format to OSS native.
  785. *
  786. */
  787. static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )
  788. {
  789. switch( paFormat )
  790. {
  791. case paUInt8:
  792. *ossFormat = AFMT_U8;
  793. break;
  794. case paInt8:
  795. *ossFormat = AFMT_S8;
  796. break;
  797. case paInt16:
  798. *ossFormat = AFMT_S16_NE;
  799. break;
  800. default:
  801. return paInternalError; /* This shouldn't happen */
  802. }
  803. return paNoError;
  804. }
  805. /** Return the PA-compatible formats that this device can support.
  806. *
  807. */
  808. static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )
  809. {
  810. PaError result = paNoError;
  811. int mask = 0;
  812. PaSampleFormat frmts = 0;
  813. ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );
  814. if( mask & AFMT_U8 )
  815. frmts |= paUInt8;
  816. if( mask & AFMT_S8 )
  817. frmts |= paInt8;
  818. if( mask & AFMT_S16_NE )
  819. frmts |= paInt16;
  820. else
  821. result = paSampleFormatNotSupported;
  822. *availableFormats = frmts;
  823. error:
  824. return result;
  825. }
  826. static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )
  827. {
  828. return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;
  829. }
  830. /** Buffer size in bytes.
  831. *
  832. */
  833. static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )
  834. {
  835. return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;
  836. }
  837. /** Configure stream component device parameters.
  838. */
  839. static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long
  840. framesPerBuffer, StreamMode streamMode, PaOssStreamComponent *master )
  841. {
  842. PaError result = paNoError;
  843. int temp, nativeFormat;
  844. int sr = (int)sampleRate;
  845. PaSampleFormat availableFormats = 0, hostFormat = 0;
  846. int chans = component->userChannelCount;
  847. int frgmt;
  848. int numBufs;
  849. int bytesPerBuf;
  850. unsigned long bufSz;
  851. unsigned long fragSz;
  852. audio_buf_info bufInfo;
  853. /* We may have a situation where only one component (the master) is configured, if both point to the same device.
  854. * In that case, the second component will copy settings from the other */
  855. if( !master )
  856. {
  857. /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.
  858. * The hardware need not respect the requested fragment size, so we may have to adapt.
  859. */
  860. if( framesPerBuffer == paFramesPerBufferUnspecified )
  861. {
  862. /* Aim for 4 fragments in the complete buffer; the latency comes from 3 of these */
  863. fragSz = (unsigned long)(component->latency * sampleRate / 3);
  864. bufSz = fragSz * 4;
  865. }
  866. else
  867. {
  868. fragSz = framesPerBuffer;
  869. bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */
  870. }
  871. PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );
  872. hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );
  873. /* OSS demands at least 2 buffers, and 16 bytes per buffer */
  874. numBufs = (int)PA_MAX( bufSz / fragSz, 2 );
  875. bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );
  876. /* The fragment parameters are encoded like this:
  877. * Most significant byte: number of fragments
  878. * Least significant byte: exponent of fragment size (i.e., for 256, 8)
  879. */
  880. frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);
  881. ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
  882. /* A: according to the OSS programmer's guide parameters should be set in this order:
  883. * format, channels, rate */
  884. /* This format should be deemed good before we get this far */
  885. PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );
  886. nativeFormat = temp;
  887. ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );
  888. PA_UNLESS( temp == nativeFormat, paInternalError );
  889. /* try to set the number of channels */
  890. ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported ); /* XXX: Should be paInvalidChannelCount? */
  891. /* It's possible that the minimum number of host channels is greater than what the user requested */
  892. PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );
  893. /* try to set the sample rate */
  894. ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );
  895. /* reject if there's no sample rate within 1% of the one requested */
  896. if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )
  897. {
  898. PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
  899. PA_ENSURE( paInvalidSampleRate );
  900. }
  901. ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),
  902. paUnanticipatedHostError );
  903. component->numBufs = bufInfo.fragstotal;
  904. /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */
  905. ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );
  906. component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;
  907. component->hostChannelCount = chans;
  908. component->hostFormat = hostFormat;
  909. }
  910. else
  911. {
  912. component->hostFormat = master->hostFormat;
  913. component->hostFrames = master->hostFrames;
  914. component->hostChannelCount = master->hostChannelCount;
  915. component->numBufs = master->numBufs;
  916. }
  917. PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),
  918. paInsufficientMemory );
  919. error:
  920. return result;
  921. }
  922. static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )
  923. {
  924. PaError result = paNoError;
  925. size_t len = *frames * PaOssStreamComponent_FrameSize( component );
  926. ssize_t bytesRead;
  927. ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );
  928. *frames = bytesRead / PaOssStreamComponent_FrameSize( component );
  929. /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */
  930. error:
  931. return result;
  932. }
  933. static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )
  934. {
  935. PaError result = paNoError;
  936. size_t len = *frames * PaOssStreamComponent_FrameSize( component );
  937. ssize_t bytesWritten;
  938. ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );
  939. *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );
  940. /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */
  941. error:
  942. return result;
  943. }
  944. /** Configure the stream according to input/output parameters.
  945. *
  946. * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by
  947. * the user, if so we'll record the actual number of host channels and adapt later.
  948. */
  949. static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,
  950. double *inputLatency, double *outputLatency )
  951. {
  952. PaError result = paNoError;
  953. int duplex = stream->capture && stream->playback;
  954. unsigned long framesPerHostBuffer = 0;
  955. /* We should request full duplex first thing after opening the device */
  956. if( duplex && stream->sharedDevice )
  957. ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );
  958. if( stream->capture )
  959. {
  960. PaOssStreamComponent *component = stream->capture;
  961. PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In,
  962. NULL ) );
  963. assert( component->hostChannelCount > 0 );
  964. assert( component->hostFrames > 0 );
  965. *inputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
  966. }
  967. if( stream->playback )
  968. {
  969. PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;
  970. PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,
  971. master ) );
  972. assert( component->hostChannelCount > 0 );
  973. assert( component->hostFrames > 0 );
  974. *outputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
  975. }
  976. if( duplex )
  977. framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );
  978. else if( stream->capture )
  979. framesPerHostBuffer = stream->capture->hostFrames;
  980. else if( stream->playback )
  981. framesPerHostBuffer = stream->playback->hostFrames;
  982. stream->framesPerHostBuffer = framesPerHostBuffer;
  983. stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate ); /* Period in usecs, rounded up */
  984. stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
  985. error:
  986. return result;
  987. }
  988. /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
  989. /** Open a PA OSS stream.
  990. *
  991. * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the
  992. * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both
  993. * directions are the same device we will demand the same number of channels. The number of channels can range
  994. * from 1 to the maximum supported by the device.
  995. *
  996. * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback
  997. * must reflect this, in addition the host latency per device should approximate the corresponding
  998. * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that
  999. * both capture and playback can agree on (they can be different devices), the buffer processor can adapt
  1000. * between host and user buffer size, but the ratio should preferably be integral.
  1001. */
  1002. static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
  1003. PaStream** s,
  1004. const PaStreamParameters *inputParameters,
  1005. const PaStreamParameters *outputParameters,
  1006. double sampleRate,
  1007. unsigned long framesPerBuffer,
  1008. PaStreamFlags streamFlags,
  1009. PaStreamCallback *streamCallback,
  1010. void *userData )
  1011. {
  1012. PaError result = paNoError;
  1013. PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
  1014. PaOssStream *stream = NULL;
  1015. int inputChannelCount = 0, outputChannelCount = 0;
  1016. PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;
  1017. const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
  1018. int bpInitialized = 0;
  1019. double inLatency = 0., outLatency = 0.;
  1020. int i = 0;
  1021. /* validate platform specific flags */
  1022. if( (streamFlags & paPlatformSpecificFlags) != 0 )
  1023. return paInvalidFlag; /* unexpected platform specific flag */
  1024. if( inputParameters )
  1025. {
  1026. /* unless alternate device specification is supported, reject the use of
  1027. paUseHostApiSpecificDeviceSpecification */
  1028. inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];
  1029. PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );
  1030. inputChannelCount = inputParameters->channelCount;
  1031. inputSampleFormat = inputParameters->sampleFormat;
  1032. }
  1033. if( outputParameters )
  1034. {
  1035. outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];
  1036. PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );
  1037. outputChannelCount = outputParameters->channelCount;
  1038. outputSampleFormat = outputParameters->sampleFormat;
  1039. }
  1040. /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same
  1041. * device is opened for both directions
  1042. */
  1043. if( inputChannelCount > 0 && outputChannelCount > 0 )
  1044. {
  1045. if( inputParameters->device == outputParameters->device )
  1046. {
  1047. if( inputParameters->channelCount != outputParameters->channelCount )
  1048. return paInvalidChannelCount;
  1049. }
  1050. }
  1051. /* Round framesPerBuffer to the next power-of-two to make OSS happy. */
  1052. if( framesPerBuffer != paFramesPerBufferUnspecified )
  1053. {
  1054. framesPerBuffer &= INT_MAX;
  1055. for (i = 1; framesPerBuffer > i; i <<= 1) ;
  1056. framesPerBuffer = i;
  1057. }
  1058. /* allocate and do basic initialization of the stream structure */
  1059. PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
  1060. PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );
  1061. PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );
  1062. PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
  1063. if( inputParameters )
  1064. {
  1065. inputHostFormat = stream->capture->hostFormat;
  1066. stream->streamRepresentation.streamInfo.inputLatency = inLatency +
  1067. PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
  1068. }
  1069. if( outputParameters )
  1070. {
  1071. outputHostFormat = stream->playback->hostFormat;
  1072. stream->streamRepresentation.streamInfo.outputLatency = outLatency +
  1073. PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
  1074. }
  1075. /* Initialize buffer processor with fixed host buffer size.
  1076. * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will
  1077. * convert between the two.
  1078. */
  1079. PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
  1080. inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,
  1081. outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,
  1082. paUtilFixedHostBufferSize, streamCallback, userData ) );
  1083. bpInitialized = 1;
  1084. *s = (PaStream*)stream;
  1085. return result;
  1086. error:
  1087. if( bpInitialized )
  1088. PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
  1089. if( stream )
  1090. PaOssStream_Terminate( stream );
  1091. return result;
  1092. }
  1093. /*! Poll on I/O filedescriptors.
  1094. Poll till we've determined there's data for read or write. In the full-duplex case,
  1095. we don't want to hang around forever waiting for either input or output frames, so
  1096. whenever we have a timed out filedescriptor we check if we're nearing under/overrun
  1097. for the other direction (critical limit set at one buffer). If so, we exit the waiting
  1098. state, and go on with what we got. We align the number of frames on a host buffer
  1099. boundary because it is possible that the buffer size differs for the two directions and
  1100. the host buffer size is a compromise between the two.
  1101. */
  1102. static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )
  1103. {
  1104. PaError result = paNoError;
  1105. int pollPlayback = 0, pollCapture = 0;
  1106. int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;
  1107. audio_buf_info bufInfo;
  1108. /* int ofs = 0, nfds = stream->nfds; */
  1109. fd_set readFds, writeFds;
  1110. int nfds = 0;
  1111. struct timeval selectTimeval = {0, 0};
  1112. unsigned long timeout = stream->pollTimeout; /* In usecs */
  1113. int captureFd = -1, playbackFd = -1;
  1114. assert( stream );
  1115. assert( frames );
  1116. if( stream->capture )
  1117. {
  1118. pollCapture = 1;
  1119. captureFd = stream->capture->fd;
  1120. /* stream->capture->pfd->events = POLLIN; */
  1121. }
  1122. if( stream->playback )
  1123. {
  1124. pollPlayback = 1;
  1125. playbackFd = stream->playback->fd;
  1126. /* stream->playback->pfd->events = POLLOUT; */
  1127. }
  1128. FD_ZERO( &readFds );
  1129. FD_ZERO( &writeFds );
  1130. while( pollPlayback || pollCapture )
  1131. {
  1132. #ifdef PTHREAD_CANCELED
  1133. pthread_testcancel();
  1134. #else
  1135. /* avoid indefinite waiting on thread not supporting cancelation */
  1136. if( stream->callbackStop || stream->callbackAbort )
  1137. {
  1138. PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
  1139. (*frames) = 0;
  1140. return paNoError;
  1141. }
  1142. #endif
  1143. /* select may modify the timeout parameter */
  1144. selectTimeval.tv_usec = timeout;
  1145. nfds = 0;
  1146. if( pollCapture )
  1147. {
  1148. FD_SET( captureFd, &readFds );
  1149. nfds = captureFd + 1;
  1150. }
  1151. if( pollPlayback )
  1152. {
  1153. FD_SET( playbackFd, &writeFds );
  1154. nfds = PA_MAX( nfds, playbackFd + 1 );
  1155. }
  1156. ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );
  1157. /*
  1158. if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )
  1159. {
  1160. ENSURE_( -1, paUnanticipatedHostError );
  1161. }
  1162. */
  1163. #ifdef PTHREAD_CANCELED
  1164. pthread_testcancel();
  1165. #else
  1166. /* avoid indefinite waiting on thread not supporting cancelation */
  1167. if( stream->callbackStop || stream->callbackAbort )
  1168. {
  1169. PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
  1170. (*frames) = 0;
  1171. return paNoError;
  1172. }
  1173. #endif
  1174. if( pollCapture )
  1175. {
  1176. if( FD_ISSET( captureFd, &readFds ) )
  1177. {
  1178. FD_CLR( captureFd, &readFds );
  1179. pollCapture = 0;
  1180. }
  1181. /*
  1182. if( stream->capture->pfd->revents & POLLIN )
  1183. {
  1184. --nfds;
  1185. ++ofs;
  1186. pollCapture = 0;
  1187. }
  1188. */
  1189. else if( stream->playback ) /* Timed out, go on with playback? */
  1190. {
  1191. /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",
  1192. __FUNCTION__, stream->pollTimeout ));*/
  1193. }
  1194. }
  1195. if( pollPlayback )
  1196. {
  1197. if( FD_ISSET( playbackFd, &writeFds ) )
  1198. {
  1199. FD_CLR( playbackFd, &writeFds );
  1200. pollPlayback = 0;
  1201. }
  1202. /*
  1203. if( stream->playback->pfd->revents & POLLOUT )
  1204. {
  1205. --nfds;
  1206. pollPlayback = 0;
  1207. }
  1208. */
  1209. else if( stream->capture ) /* Timed out, go on with capture? */
  1210. {
  1211. /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",
  1212. __FUNCTION__, stream->pollTimeout ));*/
  1213. }
  1214. }
  1215. }
  1216. if( stream->capture )
  1217. {
  1218. ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );
  1219. captureAvail = bufInfo.fragments * stream->capture->hostFrames;
  1220. if( !captureAvail )
  1221. PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));
  1222. captureAvail = captureAvail == 0 ? INT_MAX : captureAvail; /* Disregard if zero */
  1223. }
  1224. if( stream->playback )
  1225. {
  1226. ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );
  1227. playbackAvail = bufInfo.fragments * stream->playback->hostFrames;
  1228. if( !playbackAvail )
  1229. {
  1230. PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));
  1231. }
  1232. playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail; /* Disregard if zero */
  1233. }
  1234. commonAvail = PA_MIN( captureAvail, playbackAvail );
  1235. if( commonAvail == INT_MAX )
  1236. commonAvail = 0;
  1237. commonAvail -= commonAvail % stream->framesPerHostBuffer;
  1238. assert( commonAvail != INT_MAX );
  1239. assert( commonAvail >= 0 );
  1240. *frames = commonAvail;
  1241. error:
  1242. return result;
  1243. }
  1244. /** Prepare stream for capture/playback.
  1245. *
  1246. * In order to synchronize capture and playback properly we use the SETTRIGGER command.
  1247. */
  1248. static PaError PaOssStream_Prepare( PaOssStream *stream )
  1249. {
  1250. PaError result = paNoError;
  1251. int enableBits = 0;
  1252. if( stream->triggered )
  1253. return result;
  1254. /* The OSS reference instructs us to clear direction bits before setting them.*/
  1255. if( stream->playback )
  1256. ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
  1257. if( stream->capture )
  1258. ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
  1259. if( stream->playback )
  1260. {
  1261. size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
  1262. memset( stream->playback->buffer, 0, bufSz );
  1263. /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer
  1264. * OSS will complain. */
  1265. PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
  1266. while (1)
  1267. {
  1268. if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )
  1269. break;
  1270. }
  1271. PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );
  1272. }
  1273. if( stream->sharedDevice )
  1274. {
  1275. enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
  1276. ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
  1277. }
  1278. else
  1279. {
  1280. if( stream->capture )
  1281. {
  1282. enableBits = PCM_ENABLE_INPUT;
  1283. ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
  1284. }
  1285. if( stream->playback )
  1286. {
  1287. enableBits = PCM_ENABLE_OUTPUT;
  1288. ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
  1289. }
  1290. }
  1291. /* Ok, we have triggered the stream */
  1292. stream->triggered = 1;
  1293. error:
  1294. return result;
  1295. }
  1296. /** Stop audio processing
  1297. *
  1298. */
  1299. static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
  1300. {
  1301. PaError result = paNoError;
  1302. /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
  1303. * Also disable capture/playback till the stream is started again.
  1304. */
  1305. int captureErr = 0, playbackErr = 0;
  1306. if( stream->capture )
  1307. {
  1308. if( (captureErr = ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 )) < 0 )
  1309. {
  1310. PA_DEBUG(( "%s: Failed to stop capture device, error: %d\n", __FUNCTION__, captureErr ));
  1311. }
  1312. }
  1313. if( stream->playback && !stream->sharedDevice )
  1314. {
  1315. if( (playbackErr = ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 )) < 0 )
  1316. {
  1317. PA_DEBUG(( "%s: Failed to stop playback device, error: %d\n", __FUNCTION__, playbackErr ));
  1318. }
  1319. }
  1320. if( captureErr || playbackErr )
  1321. {
  1322. result = paUnanticipatedHostError;
  1323. }
  1324. return result;
  1325. }
  1326. /** Clean up after thread exit.
  1327. *
  1328. * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here
  1329. */
  1330. static void OnExit( void *data )
  1331. {
  1332. PaOssStream *stream = (PaOssStream *) data;
  1333. assert( data );
  1334. PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
  1335. PaOssStream_Stop( stream, stream->callbackAbort );
  1336. PA_DEBUG(( "OnExit: Stoppage\n" ));
  1337. /* Eventually notify user all buffers have played */
  1338. if( stream->streamRepresentation.streamFinishedCallback )
  1339. stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
  1340. stream->callbackAbort = 0; /* Clear state */
  1341. stream->isActive = 0;
  1342. }
  1343. static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )
  1344. {
  1345. PaError result = paNoError;
  1346. if( stream->capture )
  1347. {
  1348. PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,
  1349. stream->capture->hostChannelCount );
  1350. PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );
  1351. }
  1352. if( stream->playback )
  1353. {
  1354. PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,
  1355. stream->playback->hostChannelCount );
  1356. PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );
  1357. }
  1358. return result;
  1359. }
  1360. /** Thread procedure for callback processing.
  1361. *
  1362. * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the
  1363. * callback should be used for buffer priming. When the stream is cancelled a separate function will
  1364. * take care of the transition to the Callback Finished state (the stream isn't considered Stopped
  1365. * before StopStream() or AbortStream() are called).
  1366. */
  1367. static void *PaOSS_AudioThreadProc( void *userData )
  1368. {
  1369. PaError result = paNoError;
  1370. PaOssStream *stream = (PaOssStream*)userData;
  1371. unsigned long framesAvail = 0, framesProcessed = 0;
  1372. int callbackResult = paContinue;
  1373. int triggered = stream->triggered; /* See if SNDCTL_DSP_TRIGGER has been issued already */
  1374. int initiateProcessing = triggered; /* Already triggered? */
  1375. PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */
  1376. PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */
  1377. /*
  1378. #if ( SOUND_VERSION > 0x030904 )
  1379. audio_errinfo errinfo;
  1380. #endif
  1381. */
  1382. assert( stream );
  1383. pthread_cleanup_push( &OnExit, stream ); /* Execute OnExit when exiting */
  1384. /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and
  1385. * playback in sync, when the stream is restarted after being stopped we simply start by reading/
  1386. * writing.
  1387. */
  1388. PA_ENSURE( PaOssStream_Prepare( stream ) );
  1389. /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */
  1390. if( initiateProcessing )
  1391. {
  1392. /* Make sure devices are in blocking mode */
  1393. if( stream->capture )
  1394. ModifyBlocking( stream->capture->fd, 1 );
  1395. if( stream->playback )
  1396. ModifyBlocking( stream->playback->fd, 1 );
  1397. }
  1398. while( 1 )
  1399. {
  1400. #ifdef PTHREAD_CANCELED
  1401. pthread_testcancel();
  1402. #else
  1403. if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
  1404. {
  1405. PA_DEBUG(( "Aborting callback thread\n" ));
  1406. break;
  1407. }
  1408. #endif
  1409. if( stream->callbackStop && callbackResult == paContinue )
  1410. {
  1411. PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
  1412. callbackResult = paComplete;
  1413. }
  1414. /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless
  1415. * the stream has been recently started, we will have to go right ahead and read/write in blocking
  1416. * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch
  1417. * to non-blocking mode.
  1418. */
  1419. if( !initiateProcessing )
  1420. {
  1421. /* Wait on available frames */
  1422. PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) );
  1423. assert( framesAvail % stream->framesPerHostBuffer == 0 );
  1424. }
  1425. else
  1426. {
  1427. framesAvail = stream->framesPerHostBuffer;
  1428. }
  1429. while( framesAvail > 0 )
  1430. {
  1431. unsigned long frames = framesAvail;
  1432. #ifdef PTHREAD_CANCELED
  1433. pthread_testcancel();
  1434. #else
  1435. if( stream->callbackStop )
  1436. {
  1437. PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
  1438. callbackResult = paComplete;
  1439. }
  1440. if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
  1441. {
  1442. PA_DEBUG(( "Aborting callback thread\n" ));
  1443. break;
  1444. }
  1445. #endif
  1446. PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
  1447. /* Read data */
  1448. if ( stream->capture )
  1449. {
  1450. PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );
  1451. if( frames < framesAvail )
  1452. {
  1453. PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames ));
  1454. framesAvail = frames;
  1455. }
  1456. }
  1457. #if ( SOUND_VERSION >= 0x030904 )
  1458. /*
  1459. Check with OSS to see if there have been any under/overruns
  1460. since last time we checked.
  1461. */
  1462. /*
  1463. if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )
  1464. {
  1465. if( errinfo.play_underruns )
  1466. cbFlags |= paOutputUnderflow ;
  1467. if( errinfo.record_underruns )
  1468. cbFlags |= paInputUnderflow ;
  1469. }
  1470. else
  1471. PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));
  1472. */
  1473. #endif
  1474. PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
  1475. cbFlags );
  1476. cbFlags = 0;
  1477. PA_ENSURE( SetUpBuffers( stream, framesAvail ) );
  1478. framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
  1479. &callbackResult );
  1480. assert( framesProcessed == framesAvail );
  1481. PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
  1482. if ( stream->playback )
  1483. {
  1484. frames = framesAvail;
  1485. PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );
  1486. if( frames < framesAvail )
  1487. {
  1488. /* TODO: handle bytesWritten != bytesRequested (slippage?) */
  1489. PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames ));
  1490. }
  1491. }
  1492. framesAvail -= framesProcessed;
  1493. stream->framesProcessed += framesProcessed;
  1494. if( callbackResult != paContinue )
  1495. break;
  1496. }
  1497. if( initiateProcessing || !triggered )
  1498. {
  1499. /* Non-blocking */
  1500. if( stream->capture )
  1501. PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );
  1502. if( stream->playback && !stream->sharedDevice )
  1503. PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
  1504. initiateProcessing = 0;
  1505. sem_post( &stream->semaphore );
  1506. }
  1507. if( callbackResult != paContinue )
  1508. {
  1509. stream->callbackAbort = callbackResult == paAbort;
  1510. if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
  1511. break;
  1512. }
  1513. }
  1514. pthread_cleanup_pop( 1 );
  1515. error:
  1516. pthread_exit( NULL );
  1517. }
  1518. /** Close the stream.
  1519. *
  1520. */
  1521. static PaError CloseStream( PaStream* s )
  1522. {
  1523. PaError result = paNoError;
  1524. PaOssStream *stream = (PaOssStream*)s;
  1525. assert( stream );
  1526. PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
  1527. PaOssStream_Terminate( stream );
  1528. return result;
  1529. }
  1530. /** Start the stream.
  1531. *
  1532. * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual
  1533. * callback will be repeatedly called in a separate thread. If a separate thread is started this function
  1534. * will block untill it has started processing audio, otherwise audio processing is started directly.
  1535. */
  1536. static PaError StartStream( PaStream *s )
  1537. {
  1538. PaError result = paNoError;
  1539. PaOssStream *stream = (PaOssStream*)s;
  1540. stream->isActive = 1;
  1541. stream->isStopped = 0;
  1542. stream->lastPosPtr = 0;
  1543. stream->lastStreamBytes = 0;
  1544. stream->framesProcessed = 0;
  1545. /* only use the thread for callback streams */
  1546. if( stream->bufferProcessor.streamCallback )
  1547. {
  1548. PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );
  1549. sem_wait( &stream->semaphore );
  1550. }
  1551. else
  1552. PA_ENSURE( PaOssStream_Prepare( stream ) );
  1553. error:
  1554. return result;
  1555. }
  1556. static PaError RealStop( PaOssStream *stream, int abort )
  1557. {
  1558. PaError result = paNoError;
  1559. if( stream->callbackMode )
  1560. {
  1561. if( abort )
  1562. stream->callbackAbort = 1;
  1563. else
  1564. stream->callbackStop = 1;
  1565. PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );
  1566. stream->callbackStop = stream->callbackAbort = 0;
  1567. }
  1568. else
  1569. PA_ENSURE( PaOssStream_Stop( stream, abort ) );
  1570. stream->isStopped = 1;
  1571. error:
  1572. return result;
  1573. }
  1574. /** Stop the stream.
  1575. *
  1576. * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued
  1577. * buffers.
  1578. */
  1579. static PaError StopStream( PaStream *s )
  1580. {
  1581. return RealStop( (PaOssStream *)s, 0 );
  1582. }
  1583. /** Abort the stream.
  1584. *
  1585. * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued
  1586. * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing
  1587. * the OSS device.
  1588. */
  1589. static PaError AbortStream( PaStream *s )
  1590. {
  1591. return RealStop( (PaOssStream *)s, 1 );
  1592. }
  1593. /** Is the stream in the Stopped state.
  1594. *
  1595. */
  1596. static PaError IsStreamStopped( PaStream *s )
  1597. {
  1598. PaOssStream *stream = (PaOssStream*)s;
  1599. return (stream->isStopped);
  1600. }
  1601. /** Is the stream in the Active state.
  1602. *
  1603. */
  1604. static PaError IsStreamActive( PaStream *s )
  1605. {
  1606. PaOssStream *stream = (PaOssStream*)s;
  1607. return (stream->isActive);
  1608. }
  1609. static PaTime GetStreamTime( PaStream *s )
  1610. {
  1611. PaOssStream *stream = (PaOssStream*)s;
  1612. count_info info;
  1613. int delta;
  1614. if( stream->playback ) {
  1615. if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {
  1616. delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;
  1617. return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;
  1618. }
  1619. }
  1620. else {
  1621. if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {
  1622. delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;
  1623. return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;
  1624. }
  1625. }
  1626. /* the ioctl failed, but we can still give a coarse estimate */
  1627. return stream->framesProcessed / stream->sampleRate;
  1628. }
  1629. static double GetStreamCpuLoad( PaStream* s )
  1630. {
  1631. PaOssStream *stream = (PaOssStream*)s;
  1632. return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
  1633. }
  1634. /*
  1635. As separate stream interfaces are used for blocking and callback
  1636. streams, the following functions can be guaranteed to only be called
  1637. for blocking streams.
  1638. */
  1639. static PaError ReadStream( PaStream* s,
  1640. void *buffer,
  1641. unsigned long frames )
  1642. {
  1643. PaError result = paNoError;
  1644. PaOssStream *stream = (PaOssStream*)s;
  1645. int bytesRequested, bytesRead;
  1646. unsigned long framesRequested;
  1647. void *userBuffer;
  1648. /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,
  1649. * so we copy the user provided pointers */
  1650. if( stream->bufferProcessor.userInputIsInterleaved )
  1651. userBuffer = buffer;
  1652. else /* Copy channels into local array */
  1653. {
  1654. userBuffer = stream->capture->userBuffers;
  1655. memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );
  1656. }
  1657. while( frames )
  1658. {
  1659. framesRequested = PA_MIN( frames, stream->capture->hostFrames );
  1660. bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
  1661. ENSURE_( (bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested )),
  1662. paUnanticipatedHostError );
  1663. if ( bytesRequested != bytesRead )
  1664. {
  1665. PA_DEBUG(( "Requested %d bytes, read %d\n", bytesRequested, bytesRead ));
  1666. return paUnanticipatedHostError;
  1667. }
  1668. PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
  1669. PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
  1670. PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
  1671. frames -= framesRequested;
  1672. }
  1673. error:
  1674. return result;
  1675. }
  1676. static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
  1677. {
  1678. PaError result = paNoError;
  1679. PaOssStream *stream = (PaOssStream*)s;
  1680. int bytesRequested, bytesWritten;
  1681. unsigned long framesConverted;
  1682. const void *userBuffer;
  1683. /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,
  1684. * so we copy the user provided pointers */
  1685. if( stream->bufferProcessor.userOutputIsInterleaved )
  1686. userBuffer = buffer;
  1687. else
  1688. {
  1689. /* Copy channels into local array */
  1690. userBuffer = stream->playback->userBuffers;
  1691. memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );
  1692. }
  1693. while( frames )
  1694. {
  1695. PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );
  1696. PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );
  1697. framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );
  1698. frames -= framesConverted;
  1699. bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
  1700. ENSURE_( (bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested )),
  1701. paUnanticipatedHostError );
  1702. if ( bytesRequested != bytesWritten )
  1703. {
  1704. PA_DEBUG(( "Requested %d bytes, wrote %d\n", bytesRequested, bytesWritten ));
  1705. return paUnanticipatedHostError;
  1706. }
  1707. }
  1708. error:
  1709. return result;
  1710. }
  1711. static signed long GetStreamReadAvailable( PaStream* s )
  1712. {
  1713. PaError result = paNoError;
  1714. PaOssStream *stream = (PaOssStream*)s;
  1715. audio_buf_info info;
  1716. ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ), paUnanticipatedHostError );
  1717. return info.fragments * stream->capture->hostFrames;
  1718. error:
  1719. return result;
  1720. }
  1721. /* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
  1722. static signed long GetStreamWriteAvailable( PaStream* s )
  1723. {
  1724. PaError result = paNoError;
  1725. PaOssStream *stream = (PaOssStream*)s;
  1726. int delay = 0;
  1727. #ifdef SNDCTL_DSP_GETODELAY
  1728. ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ), paUnanticipatedHostError );
  1729. #endif
  1730. return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
  1731. /* Conditionally compile this to avoid warning about unused label */
  1732. #ifdef SNDCTL_DSP_GETODELAY
  1733. error:
  1734. return result;
  1735. #endif
  1736. }