Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RtAudio.cpp 344KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053
  1. /************************************************************************/
  2. /*! \class RtAudio
  3. \brief Realtime audio i/o C++ classes.
  4. RtAudio provides a common API (Application Programming Interface)
  5. for realtime audio input/output across Linux (native ALSA, Jack,
  6. and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
  7. (DirectSound, ASIO and WASAPI) operating systems.
  8. RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
  9. RtAudio: realtime audio i/o C++ classes
  10. Copyright (c) 2001-2017 Gary P. Scavone
  11. Permission is hereby granted, free of charge, to any person
  12. obtaining a copy of this software and associated documentation files
  13. (the "Software"), to deal in the Software without restriction,
  14. including without limitation the rights to use, copy, modify, merge,
  15. publish, distribute, sublicense, and/or sell copies of the Software,
  16. and to permit persons to whom the Software is furnished to do so,
  17. subject to the following conditions:
  18. The above copyright notice and this permission notice shall be
  19. included in all copies or substantial portions of the Software.
  20. Any person wishing to distribute modifications to the Software is
  21. asked to send the modifications to the original developer so that
  22. they can be incorporated into the canonical version. This is,
  23. however, not a binding provision of this license.
  24. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  27. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  28. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  29. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. */
  32. /************************************************************************/
  33. // RtAudio: Version 5.0.0
  34. #include "RtAudio.h"
  35. #include <iostream>
  36. #include <cstdlib>
  37. #include <cstring>
  38. #include <climits>
  39. #include <cmath>
  40. #include <algorithm>
  41. // Static variable definitions.
  42. const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
  43. const unsigned int RtApi::SAMPLE_RATES[] = {
  44. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  45. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  46. };
  47. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
  48. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  49. #define MUTEX_DESTROY(A) DeleteCriticalSection(A)
  50. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  51. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  52. #include "tchar.h"
  53. static std::string convertCharPointerToStdString(const char *text)
  54. {
  55. return std::string(text);
  56. }
  57. static std::string convertCharPointerToStdString(const wchar_t *text)
  58. {
  59. int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
  60. std::string s( length-1, '\0' );
  61. WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
  62. return s;
  63. }
  64. #elif defined(__LINUX_ALSA__) || defined(__UNIX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
  65. // pthread API
  66. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  67. #define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
  68. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  69. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  70. #else
  71. #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
  72. #define MUTEX_DESTROY(A) abs(*A) // dummy definitions
  73. #endif
  74. // *************************************************** //
  75. //
  76. // RtAudio definitions.
  77. //
  78. // *************************************************** //
  79. std::string RtAudio :: getVersion( void )
  80. {
  81. return RTAUDIO_VERSION;
  82. }
  83. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
  84. {
  85. apis.clear();
  86. // The order here will control the order of RtAudio's API search in
  87. // the constructor.
  88. #if defined(__UNIX_JACK__)
  89. apis.push_back( UNIX_JACK );
  90. #endif
  91. #if defined(__LINUX_ALSA__)
  92. apis.push_back( LINUX_ALSA );
  93. #endif
  94. #if defined(__UNIX_PULSE__)
  95. apis.push_back( UNIX_PULSE );
  96. #endif
  97. #if defined(__LINUX_OSS__)
  98. apis.push_back( LINUX_OSS );
  99. #endif
  100. #if defined(__WINDOWS_ASIO__)
  101. apis.push_back( WINDOWS_ASIO );
  102. #endif
  103. #if defined(__WINDOWS_WASAPI__)
  104. apis.push_back( WINDOWS_WASAPI );
  105. #endif
  106. #if defined(__WINDOWS_DS__)
  107. apis.push_back( WINDOWS_DS );
  108. #endif
  109. #if defined(__MACOSX_CORE__)
  110. apis.push_back( MACOSX_CORE );
  111. #endif
  112. #if defined(__RTAUDIO_DUMMY__)
  113. apis.push_back( RTAUDIO_DUMMY );
  114. #endif
  115. }
  116. void RtAudio :: openRtApi( RtAudio::Api api )
  117. {
  118. if ( rtapi_ )
  119. delete rtapi_;
  120. rtapi_ = 0;
  121. #if defined(__UNIX_JACK__)
  122. if ( api == UNIX_JACK )
  123. rtapi_ = new RtApiJack();
  124. #endif
  125. #if defined(__LINUX_ALSA__)
  126. if ( api == LINUX_ALSA )
  127. rtapi_ = new RtApiAlsa();
  128. #endif
  129. #if defined(__UNIX_PULSE__)
  130. if ( api == UNIX_PULSE )
  131. rtapi_ = new RtApiPulse();
  132. #endif
  133. #if defined(__LINUX_OSS__)
  134. if ( api == LINUX_OSS )
  135. rtapi_ = new RtApiOss();
  136. #endif
  137. #if defined(__WINDOWS_ASIO__)
  138. if ( api == WINDOWS_ASIO )
  139. rtapi_ = new RtApiAsio();
  140. #endif
  141. #if defined(__WINDOWS_WASAPI__)
  142. if ( api == WINDOWS_WASAPI )
  143. rtapi_ = new RtApiWasapi();
  144. #endif
  145. #if defined(__WINDOWS_DS__)
  146. if ( api == WINDOWS_DS )
  147. rtapi_ = new RtApiDs();
  148. #endif
  149. #if defined(__MACOSX_CORE__)
  150. if ( api == MACOSX_CORE )
  151. rtapi_ = new RtApiCore();
  152. #endif
  153. #if defined(__RTAUDIO_DUMMY__)
  154. if ( api == RTAUDIO_DUMMY )
  155. rtapi_ = new RtApiDummy();
  156. #endif
  157. }
  158. RtAudio :: RtAudio( RtAudio::Api api )
  159. {
  160. rtapi_ = 0;
  161. if ( api != UNSPECIFIED ) {
  162. // Attempt to open the specified API.
  163. openRtApi( api );
  164. if ( rtapi_ ) return;
  165. // No compiled support for specified API value. Issue a debug
  166. // warning and continue as if no API was specified.
  167. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  168. }
  169. // Iterate through the compiled APIs and return as soon as we find
  170. // one with at least one device or we reach the end of the list.
  171. std::vector< RtAudio::Api > apis;
  172. getCompiledApi( apis );
  173. for ( unsigned int i=0; i<apis.size(); i++ ) {
  174. openRtApi( apis[i] );
  175. if ( rtapi_ && rtapi_->getDeviceCount() ) break;
  176. }
  177. if ( rtapi_ ) return;
  178. // It should not be possible to get here because the preprocessor
  179. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  180. // API-specific definitions are passed to the compiler. But just in
  181. // case something weird happens, we'll thow an error.
  182. std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  183. throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
  184. }
  185. RtAudio :: ~RtAudio()
  186. {
  187. if ( rtapi_ )
  188. delete rtapi_;
  189. }
  190. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  191. RtAudio::StreamParameters *inputParameters,
  192. RtAudioFormat format, unsigned int sampleRate,
  193. unsigned int *bufferFrames,
  194. RtAudioCallback callback, void *userData,
  195. RtAudio::StreamOptions *options,
  196. RtAudioBufferSizeCallback bufSizeCallback,
  197. RtAudioErrorCallback errorCallback )
  198. {
  199. return rtapi_->openStream( outputParameters, inputParameters, format,
  200. sampleRate, bufferFrames, callback,
  201. userData, options, bufSizeCallback, errorCallback );
  202. }
  203. // *************************************************** //
  204. //
  205. // Public RtApi definitions (see end of file for
  206. // private or protected utility functions).
  207. //
  208. // *************************************************** //
  209. RtApi :: RtApi()
  210. {
  211. stream_.state = STREAM_CLOSED;
  212. stream_.mode = UNINITIALIZED;
  213. stream_.apiHandle = 0;
  214. stream_.userBuffer[0] = 0;
  215. stream_.userBuffer[1] = 0;
  216. MUTEX_INITIALIZE( &stream_.mutex );
  217. showWarnings_ = true;
  218. firstErrorOccurred_ = false;
  219. }
  220. RtApi :: ~RtApi()
  221. {
  222. MUTEX_DESTROY( &stream_.mutex );
  223. }
  224. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  225. RtAudio::StreamParameters *iParams,
  226. RtAudioFormat format, unsigned int sampleRate,
  227. unsigned int *bufferFrames,
  228. RtAudioCallback callback, void *userData,
  229. RtAudio::StreamOptions *options,
  230. RtAudioBufferSizeCallback bufSizeCallback,
  231. RtAudioErrorCallback errorCallback )
  232. {
  233. if ( stream_.state != STREAM_CLOSED ) {
  234. errorText_ = "RtApi::openStream: a stream is already open!";
  235. error( RtAudioError::INVALID_USE );
  236. return;
  237. }
  238. // Clear stream information potentially left from a previously open stream.
  239. clearStreamInfo();
  240. if ( oParams && oParams->nChannels < 1 ) {
  241. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  242. error( RtAudioError::INVALID_USE );
  243. return;
  244. }
  245. if ( iParams && iParams->nChannels < 1 ) {
  246. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  247. error( RtAudioError::INVALID_USE );
  248. return;
  249. }
  250. if ( oParams == NULL && iParams == NULL && getCurrentApi() != RtAudio::RTAUDIO_DUMMY ) {
  251. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  252. error( RtAudioError::INVALID_USE );
  253. return;
  254. }
  255. if ( formatBytes(format) == 0 ) {
  256. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  257. error( RtAudioError::INVALID_USE );
  258. return;
  259. }
  260. unsigned int nDevices = getDeviceCount();
  261. unsigned int oChannels = 0;
  262. if ( oParams ) {
  263. oChannels = oParams->nChannels;
  264. if ( oParams->deviceId >= nDevices ) {
  265. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  266. error( RtAudioError::INVALID_USE );
  267. return;
  268. }
  269. }
  270. unsigned int iChannels = 0;
  271. if ( iParams ) {
  272. iChannels = iParams->nChannels;
  273. if ( iParams->deviceId >= nDevices ) {
  274. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  275. error( RtAudioError::INVALID_USE );
  276. return;
  277. }
  278. }
  279. bool result;
  280. if ( oChannels > 0 ) {
  281. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  282. sampleRate, format, bufferFrames, options );
  283. if ( result == false ) {
  284. error( RtAudioError::SYSTEM_ERROR );
  285. return;
  286. }
  287. }
  288. if ( iChannels > 0 ) {
  289. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  290. sampleRate, format, bufferFrames, options );
  291. if ( result == false ) {
  292. if ( oChannels > 0 ) closeStream();
  293. error( RtAudioError::SYSTEM_ERROR );
  294. return;
  295. }
  296. }
  297. stream_.callbackInfo.callback = (void *) callback;
  298. stream_.callbackInfo.userData = userData;
  299. stream_.callbackInfo.bufSizeCallback = (void *) bufSizeCallback;
  300. stream_.callbackInfo.errorCallback = (void *) errorCallback;
  301. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  302. stream_.state = STREAM_STOPPED;
  303. }
  304. unsigned int RtApi :: getDefaultInputDevice( void )
  305. {
  306. // Should be implemented in subclasses if possible.
  307. return 0;
  308. }
  309. unsigned int RtApi :: getDefaultOutputDevice( void )
  310. {
  311. // Should be implemented in subclasses if possible.
  312. return 0;
  313. }
  314. void RtApi :: closeStream( void )
  315. {
  316. // MUST be implemented in subclasses!
  317. return;
  318. }
  319. bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
  320. unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
  321. RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
  322. RtAudio::StreamOptions * /*options*/ )
  323. {
  324. // MUST be implemented in subclasses!
  325. return FAILURE;
  326. }
  327. void RtApi :: tickStreamTime( void )
  328. {
  329. // Subclasses that do not provide their own implementation of
  330. // getStreamTime should call this function once per buffer I/O to
  331. // provide basic stream time support.
  332. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  333. #if defined( HAVE_GETTIMEOFDAY )
  334. gettimeofday( &stream_.lastTickTimestamp, NULL );
  335. #endif
  336. }
  337. long RtApi :: getStreamLatency( void )
  338. {
  339. verifyStream();
  340. long totalLatency = 0;
  341. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  342. totalLatency = stream_.latency[0];
  343. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  344. totalLatency += stream_.latency[1];
  345. return totalLatency;
  346. }
  347. double RtApi :: getStreamTime( void )
  348. {
  349. verifyStream();
  350. #if defined( HAVE_GETTIMEOFDAY )
  351. // Return a very accurate estimate of the stream time by
  352. // adding in the elapsed time since the last tick.
  353. struct timeval then;
  354. struct timeval now;
  355. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  356. return stream_.streamTime;
  357. gettimeofday( &now, NULL );
  358. then = stream_.lastTickTimestamp;
  359. return stream_.streamTime +
  360. ((now.tv_sec + 0.000001 * now.tv_usec) -
  361. (then.tv_sec + 0.000001 * then.tv_usec));
  362. #else
  363. return stream_.streamTime;
  364. #endif
  365. }
  366. void RtApi :: setStreamTime( double time )
  367. {
  368. verifyStream();
  369. if ( time >= 0.0 )
  370. stream_.streamTime = time;
  371. #if defined( HAVE_GETTIMEOFDAY )
  372. gettimeofday( &stream_.lastTickTimestamp, NULL );
  373. #endif
  374. }
  375. unsigned int RtApi :: getStreamSampleRate( void )
  376. {
  377. verifyStream();
  378. return stream_.sampleRate;
  379. }
  380. // *************************************************** //
  381. //
  382. // OS/API-specific methods.
  383. //
  384. // *************************************************** //
  385. #if defined(__MACOSX_CORE__)
  386. // The OS X CoreAudio API is designed to use a separate callback
  387. // procedure for each of its audio devices. A single RtAudio duplex
  388. // stream using two different devices is supported here, though it
  389. // cannot be guaranteed to always behave correctly because we cannot
  390. // synchronize these two callbacks.
  391. //
  392. // A property listener is installed for over/underrun information.
  393. // However, no functionality is currently provided to allow property
  394. // listeners to trigger user handlers because it is unclear what could
  395. // be done if a critical stream parameter (buffer size, sample rate,
  396. // device disconnect) notification arrived. The listeners entail
  397. // quite a bit of extra code and most likely, a user program wouldn't
  398. // be prepared for the result anyway. However, we do provide a flag
  399. // to the client callback function to inform of an over/underrun.
  400. // A structure to hold various information related to the CoreAudio API
  401. // implementation.
  402. struct CoreHandle {
  403. AudioDeviceID id[2]; // device ids
  404. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  405. AudioDeviceIOProcID procId[2];
  406. #endif
  407. UInt32 iStream[2]; // device stream index (or first if using multiple)
  408. UInt32 nStreams[2]; // number of streams to use
  409. bool xrun[2];
  410. char *deviceBuffer;
  411. pthread_cond_t condition;
  412. int drainCounter; // Tracks callback counts when draining
  413. bool internalDrain; // Indicates if stop is initiated from callback or not.
  414. CoreHandle()
  415. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  416. };
  417. RtApiCore:: RtApiCore()
  418. {
  419. #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
  420. // This is a largely undocumented but absolutely necessary
  421. // requirement starting with OS-X 10.6. If not called, queries and
  422. // updates to various audio device properties are not handled
  423. // correctly.
  424. CFRunLoopRef theRunLoop = NULL;
  425. AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
  426. kAudioObjectPropertyScopeGlobal,
  427. kAudioObjectPropertyElementMaster };
  428. OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  429. if ( result != noErr ) {
  430. errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
  431. error( RtAudioError::WARNING );
  432. }
  433. #endif
  434. }
  435. RtApiCore :: ~RtApiCore()
  436. {
  437. // The subclass destructor gets called before the base class
  438. // destructor, so close an existing stream before deallocating
  439. // apiDeviceId memory.
  440. if ( stream_.state != STREAM_CLOSED ) closeStream();
  441. }
  442. unsigned int RtApiCore :: getDeviceCount( void )
  443. {
  444. // Find out how many audio devices there are, if any.
  445. UInt32 dataSize;
  446. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  447. OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
  448. if ( result != noErr ) {
  449. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  450. error( RtAudioError::WARNING );
  451. return 0;
  452. }
  453. return dataSize / sizeof( AudioDeviceID );
  454. }
  455. unsigned int RtApiCore :: getDefaultInputDevice( void )
  456. {
  457. unsigned int nDevices = getDeviceCount();
  458. if ( nDevices <= 1 ) return 0;
  459. AudioDeviceID id;
  460. UInt32 dataSize = sizeof( AudioDeviceID );
  461. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  462. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  463. if ( result != noErr ) {
  464. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  465. error( RtAudioError::WARNING );
  466. return 0;
  467. }
  468. dataSize *= nDevices;
  469. AudioDeviceID deviceList[ nDevices ];
  470. property.mSelector = kAudioHardwarePropertyDevices;
  471. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  472. if ( result != noErr ) {
  473. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  474. error( RtAudioError::WARNING );
  475. return 0;
  476. }
  477. for ( unsigned int i=0; i<nDevices; i++ )
  478. if ( id == deviceList[i] ) return i;
  479. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  480. error( RtAudioError::WARNING );
  481. return 0;
  482. }
  483. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  484. {
  485. unsigned int nDevices = getDeviceCount();
  486. if ( nDevices <= 1 ) return 0;
  487. AudioDeviceID id;
  488. UInt32 dataSize = sizeof( AudioDeviceID );
  489. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  490. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  491. if ( result != noErr ) {
  492. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  493. error( RtAudioError::WARNING );
  494. return 0;
  495. }
  496. dataSize = sizeof( AudioDeviceID ) * nDevices;
  497. AudioDeviceID deviceList[ nDevices ];
  498. property.mSelector = kAudioHardwarePropertyDevices;
  499. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  500. if ( result != noErr ) {
  501. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  502. error( RtAudioError::WARNING );
  503. return 0;
  504. }
  505. for ( unsigned int i=0; i<nDevices; i++ )
  506. if ( id == deviceList[i] ) return i;
  507. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  508. error( RtAudioError::WARNING );
  509. return 0;
  510. }
  511. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  512. {
  513. RtAudio::DeviceInfo info;
  514. info.probed = false;
  515. // Get device ID
  516. unsigned int nDevices = getDeviceCount();
  517. if ( nDevices == 0 ) {
  518. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  519. error( RtAudioError::INVALID_USE );
  520. return info;
  521. }
  522. if ( device >= nDevices ) {
  523. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  524. error( RtAudioError::INVALID_USE );
  525. return info;
  526. }
  527. AudioDeviceID deviceList[ nDevices ];
  528. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  529. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  530. kAudioObjectPropertyScopeGlobal,
  531. kAudioObjectPropertyElementMaster };
  532. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  533. 0, NULL, &dataSize, (void *) &deviceList );
  534. if ( result != noErr ) {
  535. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  536. error( RtAudioError::WARNING );
  537. return info;
  538. }
  539. AudioDeviceID id = deviceList[ device ];
  540. // Get the device name.
  541. info.name.erase();
  542. CFStringRef cfname;
  543. dataSize = sizeof( CFStringRef );
  544. property.mSelector = kAudioObjectPropertyManufacturer;
  545. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  546. if ( result != noErr ) {
  547. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  548. errorText_ = errorStream_.str();
  549. error( RtAudioError::WARNING );
  550. return info;
  551. }
  552. //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  553. int length = CFStringGetLength(cfname);
  554. char *mname = (char *)malloc(length * 3 + 1);
  555. #if defined( UNICODE ) || defined( _UNICODE )
  556. CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
  557. #else
  558. CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
  559. #endif
  560. info.name.append( (const char *)mname, strlen(mname) );
  561. info.name.append( ": " );
  562. CFRelease( cfname );
  563. free(mname);
  564. property.mSelector = kAudioObjectPropertyName;
  565. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  566. if ( result != noErr ) {
  567. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  568. errorText_ = errorStream_.str();
  569. error( RtAudioError::WARNING );
  570. return info;
  571. }
  572. //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  573. length = CFStringGetLength(cfname);
  574. char *name = (char *)malloc(length * 3 + 1);
  575. #if defined( UNICODE ) || defined( _UNICODE )
  576. CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
  577. #else
  578. CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
  579. #endif
  580. info.name.append( (const char *)name, strlen(name) );
  581. CFRelease( cfname );
  582. free(name);
  583. // Get the output stream "configuration".
  584. AudioBufferList *bufferList = nil;
  585. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  586. property.mScope = kAudioDevicePropertyScopeOutput;
  587. // property.mElement = kAudioObjectPropertyElementWildcard;
  588. dataSize = 0;
  589. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  590. if ( result != noErr || dataSize == 0 ) {
  591. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  592. errorText_ = errorStream_.str();
  593. error( RtAudioError::WARNING );
  594. return info;
  595. }
  596. // Allocate the AudioBufferList.
  597. bufferList = (AudioBufferList *) malloc( dataSize );
  598. if ( bufferList == NULL ) {
  599. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  600. error( RtAudioError::WARNING );
  601. return info;
  602. }
  603. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  604. if ( result != noErr || dataSize == 0 ) {
  605. free( bufferList );
  606. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  607. errorText_ = errorStream_.str();
  608. error( RtAudioError::WARNING );
  609. return info;
  610. }
  611. // Get output channel information.
  612. unsigned int i, nStreams = bufferList->mNumberBuffers;
  613. for ( i=0; i<nStreams; i++ )
  614. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  615. free( bufferList );
  616. // Get the input stream "configuration".
  617. property.mScope = kAudioDevicePropertyScopeInput;
  618. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  619. if ( result != noErr || dataSize == 0 ) {
  620. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  621. errorText_ = errorStream_.str();
  622. error( RtAudioError::WARNING );
  623. return info;
  624. }
  625. // Allocate the AudioBufferList.
  626. bufferList = (AudioBufferList *) malloc( dataSize );
  627. if ( bufferList == NULL ) {
  628. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  629. error( RtAudioError::WARNING );
  630. return info;
  631. }
  632. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  633. if (result != noErr || dataSize == 0) {
  634. free( bufferList );
  635. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  636. errorText_ = errorStream_.str();
  637. error( RtAudioError::WARNING );
  638. return info;
  639. }
  640. // Get input channel information.
  641. nStreams = bufferList->mNumberBuffers;
  642. for ( i=0; i<nStreams; i++ )
  643. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  644. free( bufferList );
  645. // If device opens for both playback and capture, we determine the channels.
  646. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  647. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  648. // Probe the device sample rates.
  649. bool isInput = false;
  650. if ( info.outputChannels == 0 ) isInput = true;
  651. // Determine the supported sample rates.
  652. property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  653. if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
  654. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  655. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  656. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  657. errorText_ = errorStream_.str();
  658. error( RtAudioError::WARNING );
  659. return info;
  660. }
  661. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  662. AudioValueRange rangeList[ nRanges ];
  663. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
  664. if ( result != kAudioHardwareNoError ) {
  665. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  666. errorText_ = errorStream_.str();
  667. error( RtAudioError::WARNING );
  668. return info;
  669. }
  670. // The sample rate reporting mechanism is a bit of a mystery. It
  671. // seems that it can either return individual rates or a range of
  672. // rates. I assume that if the min / max range values are the same,
  673. // then that represents a single supported rate and if the min / max
  674. // range values are different, the device supports an arbitrary
  675. // range of values (though there might be multiple ranges, so we'll
  676. // use the most conservative range).
  677. Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
  678. bool haveValueRange = false;
  679. info.sampleRates.clear();
  680. for ( UInt32 i=0; i<nRanges; i++ ) {
  681. if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
  682. unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
  683. info.sampleRates.push_back( tmpSr );
  684. if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
  685. info.preferredSampleRate = tmpSr;
  686. } else {
  687. haveValueRange = true;
  688. if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
  689. if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
  690. }
  691. }
  692. if ( haveValueRange ) {
  693. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  694. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
  695. info.sampleRates.push_back( SAMPLE_RATES[k] );
  696. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  697. info.preferredSampleRate = SAMPLE_RATES[k];
  698. }
  699. }
  700. }
  701. // Sort and remove any redundant values
  702. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  703. info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
  704. if ( info.sampleRates.size() == 0 ) {
  705. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  706. errorText_ = errorStream_.str();
  707. error( RtAudioError::WARNING );
  708. return info;
  709. }
  710. // CoreAudio always uses 32-bit floating point data for PCM streams.
  711. // Thus, any other "physical" formats supported by the device are of
  712. // no interest to the client.
  713. info.nativeFormats = RTAUDIO_FLOAT32;
  714. if ( info.outputChannels > 0 )
  715. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  716. if ( info.inputChannels > 0 )
  717. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  718. info.probed = true;
  719. return info;
  720. }
  721. static OSStatus callbackHandler( AudioDeviceID inDevice,
  722. const AudioTimeStamp* /*inNow*/,
  723. const AudioBufferList* inInputData,
  724. const AudioTimeStamp* /*inInputTime*/,
  725. AudioBufferList* outOutputData,
  726. const AudioTimeStamp* /*inOutputTime*/,
  727. void* infoPointer )
  728. {
  729. CallbackInfo *info = (CallbackInfo *) infoPointer;
  730. RtApiCore *object = (RtApiCore *) info->object;
  731. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  732. return kAudioHardwareUnspecifiedError;
  733. else
  734. return kAudioHardwareNoError;
  735. }
  736. static OSStatus xrunListener( AudioObjectID /*inDevice*/,
  737. UInt32 nAddresses,
  738. const AudioObjectPropertyAddress properties[],
  739. void* handlePointer )
  740. {
  741. CoreHandle *handle = (CoreHandle *) handlePointer;
  742. for ( UInt32 i=0; i<nAddresses; i++ ) {
  743. if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
  744. if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
  745. handle->xrun[1] = true;
  746. else
  747. handle->xrun[0] = true;
  748. }
  749. }
  750. return kAudioHardwareNoError;
  751. }
  752. static OSStatus rateListener( AudioObjectID inDevice,
  753. UInt32 /*nAddresses*/,
  754. const AudioObjectPropertyAddress /*properties*/[],
  755. void* ratePointer )
  756. {
  757. Float64 *rate = (Float64 *) ratePointer;
  758. UInt32 dataSize = sizeof( Float64 );
  759. AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
  760. kAudioObjectPropertyScopeGlobal,
  761. kAudioObjectPropertyElementMaster };
  762. AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
  763. return kAudioHardwareNoError;
  764. }
  765. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  766. unsigned int firstChannel, unsigned int sampleRate,
  767. RtAudioFormat format, unsigned int *bufferSize,
  768. RtAudio::StreamOptions *options )
  769. {
  770. // Get device ID
  771. unsigned int nDevices = getDeviceCount();
  772. if ( nDevices == 0 ) {
  773. // This should not happen because a check is made before this function is called.
  774. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  775. return FAILURE;
  776. }
  777. if ( device >= nDevices ) {
  778. // This should not happen because a check is made before this function is called.
  779. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  780. return FAILURE;
  781. }
  782. AudioDeviceID deviceList[ nDevices ];
  783. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  784. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  785. kAudioObjectPropertyScopeGlobal,
  786. kAudioObjectPropertyElementMaster };
  787. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  788. 0, NULL, &dataSize, (void *) &deviceList );
  789. if ( result != noErr ) {
  790. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  791. return FAILURE;
  792. }
  793. AudioDeviceID id = deviceList[ device ];
  794. // Setup for stream mode.
  795. bool isInput = false;
  796. if ( mode == INPUT ) {
  797. isInput = true;
  798. property.mScope = kAudioDevicePropertyScopeInput;
  799. }
  800. else
  801. property.mScope = kAudioDevicePropertyScopeOutput;
  802. // Get the stream "configuration".
  803. AudioBufferList *bufferList = nil;
  804. dataSize = 0;
  805. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  806. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  807. if ( result != noErr || dataSize == 0 ) {
  808. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  809. errorText_ = errorStream_.str();
  810. return FAILURE;
  811. }
  812. // Allocate the AudioBufferList.
  813. bufferList = (AudioBufferList *) malloc( dataSize );
  814. if ( bufferList == NULL ) {
  815. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  816. return FAILURE;
  817. }
  818. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  819. if (result != noErr || dataSize == 0) {
  820. free( bufferList );
  821. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  822. errorText_ = errorStream_.str();
  823. return FAILURE;
  824. }
  825. // Search for one or more streams that contain the desired number of
  826. // channels. CoreAudio devices can have an arbitrary number of
  827. // streams and each stream can have an arbitrary number of channels.
  828. // For each stream, a single buffer of interleaved samples is
  829. // provided. RtAudio prefers the use of one stream of interleaved
  830. // data or multiple consecutive single-channel streams. However, we
  831. // now support multiple consecutive multi-channel streams of
  832. // interleaved data as well.
  833. UInt32 iStream, offsetCounter = firstChannel;
  834. UInt32 nStreams = bufferList->mNumberBuffers;
  835. bool monoMode = false;
  836. bool foundStream = false;
  837. // First check that the device supports the requested number of
  838. // channels.
  839. UInt32 deviceChannels = 0;
  840. for ( iStream=0; iStream<nStreams; iStream++ )
  841. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  842. if ( deviceChannels < ( channels + firstChannel ) ) {
  843. free( bufferList );
  844. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  845. errorText_ = errorStream_.str();
  846. return FAILURE;
  847. }
  848. // Look for a single stream meeting our needs.
  849. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  850. for ( iStream=0; iStream<nStreams; iStream++ ) {
  851. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  852. if ( streamChannels >= channels + offsetCounter ) {
  853. firstStream = iStream;
  854. channelOffset = offsetCounter;
  855. foundStream = true;
  856. break;
  857. }
  858. if ( streamChannels > offsetCounter ) break;
  859. offsetCounter -= streamChannels;
  860. }
  861. // If we didn't find a single stream above, then we should be able
  862. // to meet the channel specification with multiple streams.
  863. if ( foundStream == false ) {
  864. monoMode = true;
  865. offsetCounter = firstChannel;
  866. for ( iStream=0; iStream<nStreams; iStream++ ) {
  867. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  868. if ( streamChannels > offsetCounter ) break;
  869. offsetCounter -= streamChannels;
  870. }
  871. firstStream = iStream;
  872. channelOffset = offsetCounter;
  873. Int32 channelCounter = channels + offsetCounter - streamChannels;
  874. if ( streamChannels > 1 ) monoMode = false;
  875. while ( channelCounter > 0 ) {
  876. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  877. if ( streamChannels > 1 ) monoMode = false;
  878. channelCounter -= streamChannels;
  879. streamCount++;
  880. }
  881. }
  882. free( bufferList );
  883. // Determine the buffer size.
  884. AudioValueRange bufferRange;
  885. dataSize = sizeof( AudioValueRange );
  886. property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  887. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
  888. if ( result != noErr ) {
  889. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  890. errorText_ = errorStream_.str();
  891. return FAILURE;
  892. }
  893. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  894. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  895. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  896. // Set the buffer size. For multiple streams, I'm assuming we only
  897. // need to make this setting for the master channel.
  898. UInt32 theSize = (UInt32) *bufferSize;
  899. dataSize = sizeof( UInt32 );
  900. property.mSelector = kAudioDevicePropertyBufferFrameSize;
  901. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
  902. if ( result != noErr ) {
  903. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  904. errorText_ = errorStream_.str();
  905. return FAILURE;
  906. }
  907. // If attempting to setup a duplex stream, the bufferSize parameter
  908. // MUST be the same in both directions!
  909. *bufferSize = theSize;
  910. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  911. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  912. errorText_ = errorStream_.str();
  913. return FAILURE;
  914. }
  915. stream_.bufferSize = *bufferSize;
  916. stream_.nBuffers = 1;
  917. // Try to set "hog" mode ... it's not clear to me this is working.
  918. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
  919. pid_t hog_pid;
  920. dataSize = sizeof( hog_pid );
  921. property.mSelector = kAudioDevicePropertyHogMode;
  922. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
  923. if ( result != noErr ) {
  924. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
  925. errorText_ = errorStream_.str();
  926. return FAILURE;
  927. }
  928. if ( hog_pid != getpid() ) {
  929. hog_pid = getpid();
  930. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
  931. if ( result != noErr ) {
  932. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  933. errorText_ = errorStream_.str();
  934. return FAILURE;
  935. }
  936. }
  937. }
  938. // Check and if necessary, change the sample rate for the device.
  939. Float64 nominalRate;
  940. dataSize = sizeof( Float64 );
  941. property.mSelector = kAudioDevicePropertyNominalSampleRate;
  942. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
  943. if ( result != noErr ) {
  944. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
  945. errorText_ = errorStream_.str();
  946. return FAILURE;
  947. }
  948. // Only change the sample rate if off by more than 1 Hz.
  949. if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
  950. // Set a property listener for the sample rate change
  951. Float64 reportedRate = 0.0;
  952. AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  953. result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  954. if ( result != noErr ) {
  955. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";
  956. errorText_ = errorStream_.str();
  957. return FAILURE;
  958. }
  959. nominalRate = (Float64) sampleRate;
  960. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
  961. if ( result != noErr ) {
  962. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  963. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";
  964. errorText_ = errorStream_.str();
  965. return FAILURE;
  966. }
  967. // Now wait until the reported nominal rate is what we just set.
  968. UInt32 microCounter = 0;
  969. while ( reportedRate != nominalRate ) {
  970. microCounter += 5000;
  971. if ( microCounter > 5000000 ) break;
  972. usleep( 5000 );
  973. }
  974. // Remove the property listener.
  975. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  976. if ( microCounter > 5000000 ) {
  977. errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
  978. errorText_ = errorStream_.str();
  979. return FAILURE;
  980. }
  981. }
  982. // Now set the stream format for all streams. Also, check the
  983. // physical format of the device and change that if necessary.
  984. AudioStreamBasicDescription description;
  985. dataSize = sizeof( AudioStreamBasicDescription );
  986. property.mSelector = kAudioStreamPropertyVirtualFormat;
  987. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  988. if ( result != noErr ) {
  989. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  990. errorText_ = errorStream_.str();
  991. return FAILURE;
  992. }
  993. // Set the sample rate and data format id. However, only make the
  994. // change if the sample rate is not within 1.0 of the desired
  995. // rate and the format is not linear pcm.
  996. bool updateFormat = false;
  997. if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
  998. description.mSampleRate = (Float64) sampleRate;
  999. updateFormat = true;
  1000. }
  1001. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  1002. description.mFormatID = kAudioFormatLinearPCM;
  1003. updateFormat = true;
  1004. }
  1005. if ( updateFormat ) {
  1006. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
  1007. if ( result != noErr ) {
  1008. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  1009. errorText_ = errorStream_.str();
  1010. return FAILURE;
  1011. }
  1012. }
  1013. // Now check the physical format.
  1014. property.mSelector = kAudioStreamPropertyPhysicalFormat;
  1015. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1016. if ( result != noErr ) {
  1017. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  1018. errorText_ = errorStream_.str();
  1019. return FAILURE;
  1020. }
  1021. //std::cout << "Current physical stream format:" << std::endl;
  1022. //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
  1023. //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1024. //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
  1025. //std::cout << " sample rate = " << description.mSampleRate << std::endl;
  1026. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
  1027. description.mFormatID = kAudioFormatLinearPCM;
  1028. //description.mSampleRate = (Float64) sampleRate;
  1029. AudioStreamBasicDescription testDescription = description;
  1030. UInt32 formatFlags;
  1031. // We'll try higher bit rates first and then work our way down.
  1032. std::vector< std::pair<UInt32, UInt32> > physicalFormats;
  1033. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
  1034. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1035. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1036. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1037. physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
  1038. formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
  1039. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
  1040. formatFlags |= kAudioFormatFlagIsAlignedHigh;
  1041. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
  1042. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1043. physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
  1044. physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
  1045. bool setPhysicalFormat = false;
  1046. for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
  1047. testDescription = description;
  1048. testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
  1049. testDescription.mFormatFlags = physicalFormats[i].second;
  1050. if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
  1051. testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
  1052. else
  1053. testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
  1054. testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
  1055. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
  1056. if ( result == noErr ) {
  1057. setPhysicalFormat = true;
  1058. //std::cout << "Updated physical stream format:" << std::endl;
  1059. //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
  1060. //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1061. //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
  1062. //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
  1063. break;
  1064. }
  1065. }
  1066. if ( !setPhysicalFormat ) {
  1067. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  1068. errorText_ = errorStream_.str();
  1069. return FAILURE;
  1070. }
  1071. } // done setting virtual/physical formats.
  1072. // Get the stream / device latency.
  1073. UInt32 latency;
  1074. dataSize = sizeof( UInt32 );
  1075. property.mSelector = kAudioDevicePropertyLatency;
  1076. if ( AudioObjectHasProperty( id, &property ) == true ) {
  1077. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
  1078. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  1079. else {
  1080. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  1081. errorText_ = errorStream_.str();
  1082. error( RtAudioError::WARNING );
  1083. }
  1084. }
  1085. // Byte-swapping: According to AudioHardware.h, the stream data will
  1086. // always be presented in native-endian format, so we should never
  1087. // need to byte swap.
  1088. stream_.doByteSwap[mode] = false;
  1089. // From the CoreAudio documentation, PCM data must be supplied as
  1090. // 32-bit floats.
  1091. stream_.userFormat = format;
  1092. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1093. if ( streamCount == 1 )
  1094. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  1095. else // multiple streams
  1096. stream_.nDeviceChannels[mode] = channels;
  1097. stream_.nUserChannels[mode] = channels;
  1098. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  1099. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1100. else stream_.userInterleaved = true;
  1101. stream_.deviceInterleaved[mode] = true;
  1102. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  1103. // Set flags for buffer conversion.
  1104. stream_.doConvertBuffer[mode] = false;
  1105. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1106. stream_.doConvertBuffer[mode] = true;
  1107. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  1108. stream_.doConvertBuffer[mode] = true;
  1109. if ( streamCount == 1 ) {
  1110. if ( stream_.nUserChannels[mode] > 1 &&
  1111. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  1112. stream_.doConvertBuffer[mode] = true;
  1113. }
  1114. else if ( monoMode && stream_.userInterleaved )
  1115. stream_.doConvertBuffer[mode] = true;
  1116. // Allocate our CoreHandle structure for the stream.
  1117. CoreHandle *handle = 0;
  1118. if ( stream_.apiHandle == 0 ) {
  1119. try {
  1120. handle = new CoreHandle;
  1121. }
  1122. catch ( std::bad_alloc& ) {
  1123. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  1124. goto error;
  1125. }
  1126. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  1127. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  1128. goto error;
  1129. }
  1130. stream_.apiHandle = (void *) handle;
  1131. }
  1132. else
  1133. handle = (CoreHandle *) stream_.apiHandle;
  1134. handle->iStream[mode] = firstStream;
  1135. handle->nStreams[mode] = streamCount;
  1136. handle->id[mode] = id;
  1137. // Allocate necessary internal buffers.
  1138. unsigned long bufferBytes;
  1139. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1140. // stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1141. stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );
  1142. memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );
  1143. if ( stream_.userBuffer[mode] == NULL ) {
  1144. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  1145. goto error;
  1146. }
  1147. // If possible, we will make use of the CoreAudio stream buffers as
  1148. // "device buffers". However, we can't do this if using multiple
  1149. // streams.
  1150. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  1151. bool makeBuffer = true;
  1152. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  1153. if ( mode == INPUT ) {
  1154. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1155. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1156. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  1157. }
  1158. }
  1159. if ( makeBuffer ) {
  1160. bufferBytes *= *bufferSize;
  1161. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1162. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1163. if ( stream_.deviceBuffer == NULL ) {
  1164. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  1165. goto error;
  1166. }
  1167. }
  1168. }
  1169. stream_.sampleRate = sampleRate;
  1170. stream_.device[mode] = device;
  1171. stream_.state = STREAM_STOPPED;
  1172. stream_.callbackInfo.object = (void *) this;
  1173. // Setup the buffer conversion information structure.
  1174. if ( stream_.doConvertBuffer[mode] ) {
  1175. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  1176. else setConvertInfo( mode, channelOffset );
  1177. }
  1178. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1179. // Only one callback procedure per device.
  1180. stream_.mode = DUPLEX;
  1181. else {
  1182. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1183. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1184. #else
  1185. // deprecated in favor of AudioDeviceCreateIOProcID()
  1186. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1187. #endif
  1188. if ( result != noErr ) {
  1189. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1190. errorText_ = errorStream_.str();
  1191. goto error;
  1192. }
  1193. if ( stream_.mode == OUTPUT && mode == INPUT )
  1194. stream_.mode = DUPLEX;
  1195. else
  1196. stream_.mode = mode;
  1197. }
  1198. // Setup the device property listener for over/underload.
  1199. property.mSelector = kAudioDeviceProcessorOverload;
  1200. property.mScope = kAudioObjectPropertyScopeGlobal;
  1201. result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
  1202. return SUCCESS;
  1203. error:
  1204. if ( handle ) {
  1205. pthread_cond_destroy( &handle->condition );
  1206. delete handle;
  1207. stream_.apiHandle = 0;
  1208. }
  1209. for ( int i=0; i<2; i++ ) {
  1210. if ( stream_.userBuffer[i] ) {
  1211. free( stream_.userBuffer[i] );
  1212. stream_.userBuffer[i] = 0;
  1213. }
  1214. }
  1215. if ( stream_.deviceBuffer ) {
  1216. free( stream_.deviceBuffer );
  1217. stream_.deviceBuffer = 0;
  1218. }
  1219. stream_.state = STREAM_CLOSED;
  1220. return FAILURE;
  1221. }
  1222. void RtApiCore :: closeStream( void )
  1223. {
  1224. if ( stream_.state == STREAM_CLOSED ) {
  1225. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1226. error( RtAudioError::WARNING );
  1227. return;
  1228. }
  1229. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1230. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1231. if (handle) {
  1232. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1233. kAudioObjectPropertyScopeGlobal,
  1234. kAudioObjectPropertyElementMaster };
  1235. property.mSelector = kAudioDeviceProcessorOverload;
  1236. property.mScope = kAudioObjectPropertyScopeGlobal;
  1237. if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {
  1238. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1239. error( RtAudioError::WARNING );
  1240. }
  1241. }
  1242. if ( stream_.state == STREAM_RUNNING )
  1243. AudioDeviceStop( handle->id[0], callbackHandler );
  1244. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1245. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1246. #else
  1247. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1248. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1249. #endif
  1250. }
  1251. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1252. if (handle) {
  1253. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1254. kAudioObjectPropertyScopeGlobal,
  1255. kAudioObjectPropertyElementMaster };
  1256. property.mSelector = kAudioDeviceProcessorOverload;
  1257. property.mScope = kAudioObjectPropertyScopeGlobal;
  1258. if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {
  1259. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1260. error( RtAudioError::WARNING );
  1261. }
  1262. }
  1263. if ( stream_.state == STREAM_RUNNING )
  1264. AudioDeviceStop( handle->id[1], callbackHandler );
  1265. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1266. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1267. #else
  1268. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1269. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1270. #endif
  1271. }
  1272. for ( int i=0; i<2; i++ ) {
  1273. if ( stream_.userBuffer[i] ) {
  1274. free( stream_.userBuffer[i] );
  1275. stream_.userBuffer[i] = 0;
  1276. }
  1277. }
  1278. if ( stream_.deviceBuffer ) {
  1279. free( stream_.deviceBuffer );
  1280. stream_.deviceBuffer = 0;
  1281. }
  1282. // Destroy pthread condition variable.
  1283. pthread_cond_destroy( &handle->condition );
  1284. delete handle;
  1285. stream_.apiHandle = 0;
  1286. stream_.mode = UNINITIALIZED;
  1287. stream_.state = STREAM_CLOSED;
  1288. }
  1289. void RtApiCore :: startStream( void )
  1290. {
  1291. verifyStream();
  1292. if ( stream_.state == STREAM_RUNNING ) {
  1293. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1294. error( RtAudioError::WARNING );
  1295. return;
  1296. }
  1297. OSStatus result = noErr;
  1298. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1299. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1300. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1301. if ( result != noErr ) {
  1302. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1303. errorText_ = errorStream_.str();
  1304. goto unlock;
  1305. }
  1306. }
  1307. if ( stream_.mode == INPUT ||
  1308. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1309. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1310. if ( result != noErr ) {
  1311. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1312. errorText_ = errorStream_.str();
  1313. goto unlock;
  1314. }
  1315. }
  1316. handle->drainCounter = 0;
  1317. handle->internalDrain = false;
  1318. stream_.state = STREAM_RUNNING;
  1319. unlock:
  1320. if ( result == noErr ) return;
  1321. error( RtAudioError::SYSTEM_ERROR );
  1322. }
  1323. void RtApiCore :: stopStream( void )
  1324. {
  1325. verifyStream();
  1326. if ( stream_.state == STREAM_STOPPED ) {
  1327. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1328. error( RtAudioError::WARNING );
  1329. return;
  1330. }
  1331. OSStatus result = noErr;
  1332. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1333. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1334. if ( handle->drainCounter == 0 ) {
  1335. handle->drainCounter = 2;
  1336. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1337. }
  1338. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1339. if ( result != noErr ) {
  1340. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1341. errorText_ = errorStream_.str();
  1342. goto unlock;
  1343. }
  1344. }
  1345. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1346. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1347. if ( result != noErr ) {
  1348. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1349. errorText_ = errorStream_.str();
  1350. goto unlock;
  1351. }
  1352. }
  1353. stream_.state = STREAM_STOPPED;
  1354. unlock:
  1355. if ( result == noErr ) return;
  1356. error( RtAudioError::SYSTEM_ERROR );
  1357. }
  1358. void RtApiCore :: abortStream( void )
  1359. {
  1360. verifyStream();
  1361. if ( stream_.state == STREAM_STOPPED ) {
  1362. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1363. error( RtAudioError::WARNING );
  1364. return;
  1365. }
  1366. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1367. handle->drainCounter = 2;
  1368. stopStream();
  1369. }
  1370. // This function will be called by a spawned thread when the user
  1371. // callback function signals that the stream should be stopped or
  1372. // aborted. It is better to handle it this way because the
  1373. // callbackEvent() function probably should return before the AudioDeviceStop()
  1374. // function is called.
  1375. static void *coreStopStream( void *ptr )
  1376. {
  1377. CallbackInfo *info = (CallbackInfo *) ptr;
  1378. RtApiCore *object = (RtApiCore *) info->object;
  1379. object->stopStream();
  1380. pthread_exit( NULL );
  1381. return NULL;
  1382. }
  1383. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1384. const AudioBufferList *inBufferList,
  1385. const AudioBufferList *outBufferList )
  1386. {
  1387. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  1388. if ( stream_.state == STREAM_CLOSED ) {
  1389. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1390. error( RtAudioError::WARNING );
  1391. return FAILURE;
  1392. }
  1393. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1394. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1395. // Check if we were draining the stream and signal is finished.
  1396. if ( handle->drainCounter > 3 ) {
  1397. ThreadHandle threadId;
  1398. stream_.state = STREAM_STOPPING;
  1399. if ( handle->internalDrain == true )
  1400. pthread_create( &threadId, NULL, coreStopStream, info );
  1401. else // external call to stopStream()
  1402. pthread_cond_signal( &handle->condition );
  1403. return SUCCESS;
  1404. }
  1405. AudioDeviceID outputDevice = handle->id[0];
  1406. // Invoke user callback to get fresh output data UNLESS we are
  1407. // draining stream or duplex mode AND the input/output devices are
  1408. // different AND this function is called for the input device.
  1409. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1410. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1411. double streamTime = getStreamTime();
  1412. RtAudioStreamStatus status = 0;
  1413. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1414. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1415. handle->xrun[0] = false;
  1416. }
  1417. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1418. status |= RTAUDIO_INPUT_OVERFLOW;
  1419. handle->xrun[1] = false;
  1420. }
  1421. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1422. stream_.bufferSize, streamTime, status, info->userData );
  1423. if ( cbReturnValue == 2 ) {
  1424. stream_.state = STREAM_STOPPING;
  1425. handle->drainCounter = 2;
  1426. abortStream();
  1427. return SUCCESS;
  1428. }
  1429. else if ( cbReturnValue == 1 ) {
  1430. handle->drainCounter = 1;
  1431. handle->internalDrain = true;
  1432. }
  1433. }
  1434. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1435. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1436. if ( handle->nStreams[0] == 1 ) {
  1437. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1438. 0,
  1439. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1440. }
  1441. else { // fill multiple streams with zeros
  1442. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1443. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1444. 0,
  1445. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1446. }
  1447. }
  1448. }
  1449. else if ( handle->nStreams[0] == 1 ) {
  1450. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1451. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1452. stream_.userBuffer[0], stream_.convertInfo[0] );
  1453. }
  1454. else { // copy from user buffer
  1455. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1456. stream_.userBuffer[0],
  1457. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1458. }
  1459. }
  1460. else { // fill multiple streams
  1461. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1462. if ( stream_.doConvertBuffer[0] ) {
  1463. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1464. inBuffer = (Float32 *) stream_.deviceBuffer;
  1465. }
  1466. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1467. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1468. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1469. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1470. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1471. }
  1472. }
  1473. else { // fill multiple multi-channel streams with interleaved data
  1474. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1475. Float32 *out, *in;
  1476. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1477. UInt32 inChannels = stream_.nUserChannels[0];
  1478. if ( stream_.doConvertBuffer[0] ) {
  1479. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1480. inChannels = stream_.nDeviceChannels[0];
  1481. }
  1482. if ( inInterleaved ) inOffset = 1;
  1483. else inOffset = stream_.bufferSize;
  1484. channelsLeft = inChannels;
  1485. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1486. in = inBuffer;
  1487. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1488. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1489. outJump = 0;
  1490. // Account for possible channel offset in first stream
  1491. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1492. streamChannels -= stream_.channelOffset[0];
  1493. outJump = stream_.channelOffset[0];
  1494. out += outJump;
  1495. }
  1496. // Account for possible unfilled channels at end of the last stream
  1497. if ( streamChannels > channelsLeft ) {
  1498. outJump = streamChannels - channelsLeft;
  1499. streamChannels = channelsLeft;
  1500. }
  1501. // Determine input buffer offsets and skips
  1502. if ( inInterleaved ) {
  1503. inJump = inChannels;
  1504. in += inChannels - channelsLeft;
  1505. }
  1506. else {
  1507. inJump = 1;
  1508. in += (inChannels - channelsLeft) * inOffset;
  1509. }
  1510. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1511. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1512. *out++ = in[j*inOffset];
  1513. }
  1514. out += outJump;
  1515. in += inJump;
  1516. }
  1517. channelsLeft -= streamChannels;
  1518. }
  1519. }
  1520. }
  1521. }
  1522. // Don't bother draining input
  1523. if ( handle->drainCounter ) {
  1524. handle->drainCounter++;
  1525. goto unlock;
  1526. }
  1527. AudioDeviceID inputDevice;
  1528. inputDevice = handle->id[1];
  1529. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1530. if ( handle->nStreams[1] == 1 ) {
  1531. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1532. convertBuffer( stream_.userBuffer[1],
  1533. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1534. stream_.convertInfo[1] );
  1535. }
  1536. else { // copy to user buffer
  1537. memcpy( stream_.userBuffer[1],
  1538. inBufferList->mBuffers[handle->iStream[1]].mData,
  1539. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1540. }
  1541. }
  1542. else { // read from multiple streams
  1543. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1544. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1545. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1546. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1547. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1548. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1549. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1550. }
  1551. }
  1552. else { // read from multiple multi-channel streams
  1553. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1554. Float32 *out, *in;
  1555. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1556. UInt32 outChannels = stream_.nUserChannels[1];
  1557. if ( stream_.doConvertBuffer[1] ) {
  1558. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1559. outChannels = stream_.nDeviceChannels[1];
  1560. }
  1561. if ( outInterleaved ) outOffset = 1;
  1562. else outOffset = stream_.bufferSize;
  1563. channelsLeft = outChannels;
  1564. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1565. out = outBuffer;
  1566. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1567. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1568. inJump = 0;
  1569. // Account for possible channel offset in first stream
  1570. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1571. streamChannels -= stream_.channelOffset[1];
  1572. inJump = stream_.channelOffset[1];
  1573. in += inJump;
  1574. }
  1575. // Account for possible unread channels at end of the last stream
  1576. if ( streamChannels > channelsLeft ) {
  1577. inJump = streamChannels - channelsLeft;
  1578. streamChannels = channelsLeft;
  1579. }
  1580. // Determine output buffer offsets and skips
  1581. if ( outInterleaved ) {
  1582. outJump = outChannels;
  1583. out += outChannels - channelsLeft;
  1584. }
  1585. else {
  1586. outJump = 1;
  1587. out += (outChannels - channelsLeft) * outOffset;
  1588. }
  1589. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1590. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1591. out[j*outOffset] = *in++;
  1592. }
  1593. out += outJump;
  1594. in += inJump;
  1595. }
  1596. channelsLeft -= streamChannels;
  1597. }
  1598. }
  1599. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1600. convertBuffer( stream_.userBuffer[1],
  1601. stream_.deviceBuffer,
  1602. stream_.convertInfo[1] );
  1603. }
  1604. }
  1605. }
  1606. unlock:
  1607. //MUTEX_UNLOCK( &stream_.mutex );
  1608. RtApi::tickStreamTime();
  1609. return SUCCESS;
  1610. }
  1611. const char* RtApiCore :: getErrorCode( OSStatus code )
  1612. {
  1613. switch( code ) {
  1614. case kAudioHardwareNotRunningError:
  1615. return "kAudioHardwareNotRunningError";
  1616. case kAudioHardwareUnspecifiedError:
  1617. return "kAudioHardwareUnspecifiedError";
  1618. case kAudioHardwareUnknownPropertyError:
  1619. return "kAudioHardwareUnknownPropertyError";
  1620. case kAudioHardwareBadPropertySizeError:
  1621. return "kAudioHardwareBadPropertySizeError";
  1622. case kAudioHardwareIllegalOperationError:
  1623. return "kAudioHardwareIllegalOperationError";
  1624. case kAudioHardwareBadObjectError:
  1625. return "kAudioHardwareBadObjectError";
  1626. case kAudioHardwareBadDeviceError:
  1627. return "kAudioHardwareBadDeviceError";
  1628. case kAudioHardwareBadStreamError:
  1629. return "kAudioHardwareBadStreamError";
  1630. case kAudioHardwareUnsupportedOperationError:
  1631. return "kAudioHardwareUnsupportedOperationError";
  1632. case kAudioDeviceUnsupportedFormatError:
  1633. return "kAudioDeviceUnsupportedFormatError";
  1634. case kAudioDevicePermissionsError:
  1635. return "kAudioDevicePermissionsError";
  1636. default:
  1637. return "CoreAudio unknown error";
  1638. }
  1639. }
  1640. //******************** End of __MACOSX_CORE__ *********************//
  1641. #endif
  1642. #if defined(__UNIX_JACK__)
  1643. // JACK is a low-latency audio server, originally written for the
  1644. // GNU/Linux operating system and now also ported to OS-X. It can
  1645. // connect a number of different applications to an audio device, as
  1646. // well as allowing them to share audio between themselves.
  1647. //
  1648. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1649. // have ports connected to the server. The JACK server is typically
  1650. // started in a terminal as follows:
  1651. //
  1652. // .jackd -d alsa -d hw:0
  1653. //
  1654. // or through an interface program such as qjackctl. Many of the
  1655. // parameters normally set for a stream are fixed by the JACK server
  1656. // and can be specified when the JACK server is started. In
  1657. // particular,
  1658. //
  1659. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1660. //
  1661. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1662. // frames, and number of buffers = 4. Once the server is running, it
  1663. // is not possible to override these values. If the values are not
  1664. // specified in the command-line, the JACK server uses default values.
  1665. //
  1666. // The JACK server does not have to be running when an instance of
  1667. // RtApiJack is created, though the function getDeviceCount() will
  1668. // report 0 devices found until JACK has been started. When no
  1669. // devices are available (i.e., the JACK server is not running), a
  1670. // stream cannot be opened.
  1671. #include "jackbridge/JackBridge.hpp"
  1672. #include <unistd.h>
  1673. #include <cstdio>
  1674. // A structure to hold various information related to the Jack API
  1675. // implementation.
  1676. struct JackHandle {
  1677. jack_client_t *client;
  1678. jack_port_t **ports[2];
  1679. bool xrun[2];
  1680. pthread_cond_t condition;
  1681. int drainCounter; // Tracks callback counts when draining
  1682. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1683. JackHandle()
  1684. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1685. };
  1686. RtApiJack :: RtApiJack()
  1687. :shouldAutoconnect_(true) {
  1688. // Nothing to do here.
  1689. }
  1690. RtApiJack :: ~RtApiJack()
  1691. {
  1692. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1693. }
  1694. unsigned int RtApiJack :: getDeviceCount( void )
  1695. {
  1696. return 2;
  1697. }
  1698. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1699. {
  1700. static RtAudio::DeviceInfo devInfo[3];
  1701. if (! devInfo[0].probed)
  1702. {
  1703. devInfo[0].probed = devInfo[1].probed = true;
  1704. devInfo[0].outputChannels = devInfo[1].outputChannels = 2;
  1705. devInfo[0].inputChannels = devInfo[1].inputChannels = 2;
  1706. devInfo[0].duplexChannels = devInfo[1].duplexChannels = 2;
  1707. devInfo[0].isDefaultOutput = devInfo[1].isDefaultOutput = true;
  1708. devInfo[0].isDefaultInput = devInfo[1].isDefaultInput = true;
  1709. devInfo[0].nativeFormats = devInfo[1].nativeFormats = RTAUDIO_FLOAT32;
  1710. devInfo[0].name = "Auto-connect ON";
  1711. devInfo[1].name = "Auto-connect OFF";
  1712. }
  1713. if (device > 2)
  1714. device = 2;
  1715. return devInfo[device];
  1716. }
  1717. static int jackBufferSizeHandler( jack_nframes_t nframes, void *infoPointer )
  1718. {
  1719. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1720. RtApiJack *object = (RtApiJack *) info->object;
  1721. if ( object->bufferSizeEvent( (unsigned long) nframes ) == false ) return 1;
  1722. return 0;
  1723. }
  1724. static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1725. {
  1726. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1727. RtApiJack *object = (RtApiJack *) info->object;
  1728. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1729. return 0;
  1730. }
  1731. // This function will be called by a spawned thread when the Jack
  1732. // server signals that it is shutting down. It is necessary to handle
  1733. // it this way because the jackShutdown() function must return before
  1734. // the jackbridge_deactivate() function (in closeStream()) will return.
  1735. static void *jackCloseStream( void *ptr )
  1736. {
  1737. CallbackInfo *info = (CallbackInfo *) ptr;
  1738. RtApiJack *object = (RtApiJack *) info->object;
  1739. object->closeStream();
  1740. pthread_exit( NULL );
  1741. return NULL;
  1742. }
  1743. static void jackShutdown( void *infoPointer )
  1744. {
  1745. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1746. RtApiJack *object = (RtApiJack *) info->object;
  1747. // Check current stream state. If stopped, then we'll assume this
  1748. // was called as a result of a call to RtApiJack::stopStream (the
  1749. // deactivation of a client handle causes this function to be called).
  1750. // If not, we'll assume the Jack server is shutting down or some
  1751. // other problem occurred and we should close the stream.
  1752. if ( object->isStreamRunning() == false ) return;
  1753. ThreadHandle threadId;
  1754. pthread_create( &threadId, NULL, jackCloseStream, info );
  1755. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1756. }
  1757. static int jackXrun( void *infoPointer )
  1758. {
  1759. JackHandle *handle = *((JackHandle **) infoPointer);
  1760. if ( handle->ports[0] ) handle->xrun[0] = true;
  1761. if ( handle->ports[1] ) handle->xrun[1] = true;
  1762. return 0;
  1763. }
  1764. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1765. unsigned int firstChannel, unsigned int sampleRate,
  1766. RtAudioFormat format, unsigned int *bufferSize,
  1767. RtAudio::StreamOptions *options )
  1768. {
  1769. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1770. // Look for jack server and try to become a client (only do once per stream).
  1771. jack_client_t *client = 0;
  1772. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1773. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1774. jack_status_t *status = NULL;
  1775. if ( options && !options->streamName.empty() )
  1776. client = jackbridge_client_open( options->streamName.c_str(), jackoptions, status );
  1777. else
  1778. client = jackbridge_client_open( "Carla", jackoptions, status );
  1779. if ( client == 0 ) {
  1780. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1781. error( RtAudioError::WARNING );
  1782. return FAILURE;
  1783. }
  1784. }
  1785. else {
  1786. // The handle must have been created on an earlier pass.
  1787. client = handle->client;
  1788. }
  1789. // Check the jack server sample rate.
  1790. unsigned int jackRate = jackbridge_get_sample_rate( client );
  1791. if ( sampleRate != jackRate ) {
  1792. std::cerr << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ")." << std::endl;
  1793. }
  1794. stream_.sampleRate = jackRate;
  1795. // Get the latency of the JACK port.
  1796. const char **ports;
  1797. ports = jackbridge_get_ports( client, "system:", NULL, JackPortIsInput );
  1798. if ( ports[ firstChannel ] ) {
  1799. // Added by Ge Wang
  1800. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  1801. // the range (usually the min and max are equal)
  1802. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  1803. // get the latency range
  1804. jackbridge_port_get_latency_range( jackbridge_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  1805. // be optimistic, use the min!
  1806. stream_.latency[mode] = latrange.min;
  1807. //stream_.latency[mode] = jack_port_get_latency( jackbridge_port_by_name( client, ports[ firstChannel ] ) );
  1808. }
  1809. jackbridge_free( ports );
  1810. // The jack server always uses 32-bit floating-point data.
  1811. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1812. stream_.userFormat = format;
  1813. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1814. else stream_.userInterleaved = true;
  1815. // Jack always uses non-interleaved buffers.
  1816. stream_.deviceInterleaved[mode] = false;
  1817. // Jack always provides host byte-ordered data.
  1818. stream_.doByteSwap[mode] = false;
  1819. // Get the buffer size. The buffer size and number of buffers
  1820. // (periods) is set when the jack server is started.
  1821. stream_.bufferSize = (int) jackbridge_get_buffer_size( client );
  1822. *bufferSize = stream_.bufferSize;
  1823. stream_.nDeviceChannels[mode] = channels;
  1824. stream_.nUserChannels[mode] = channels;
  1825. // Set flags for buffer conversion.
  1826. stream_.doConvertBuffer[mode] = false;
  1827. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1828. stream_.doConvertBuffer[mode] = true;
  1829. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  1830. stream_.nUserChannels[mode] > 1 )
  1831. stream_.doConvertBuffer[mode] = true;
  1832. // Allocate our JackHandle structure for the stream.
  1833. if ( handle == 0 ) {
  1834. try {
  1835. handle = new JackHandle;
  1836. }
  1837. catch ( std::bad_alloc& ) {
  1838. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  1839. goto error;
  1840. }
  1841. if ( pthread_cond_init(&handle->condition, NULL) ) {
  1842. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  1843. goto error;
  1844. }
  1845. stream_.apiHandle = (void *) handle;
  1846. handle->client = client;
  1847. }
  1848. // Allocate necessary internal buffers.
  1849. unsigned long bufferBytes;
  1850. bufferBytes = stream_.nUserChannels[mode] * 8192 * formatBytes( stream_.userFormat );
  1851. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1852. if ( stream_.userBuffer[mode] == NULL ) {
  1853. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  1854. goto error;
  1855. }
  1856. if ( stream_.doConvertBuffer[mode] ) {
  1857. bool makeBuffer = true;
  1858. if ( mode == OUTPUT )
  1859. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1860. else { // mode == INPUT
  1861. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  1862. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1863. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  1864. if ( bufferBytes < bytesOut ) makeBuffer = false;
  1865. }
  1866. }
  1867. if ( makeBuffer ) {
  1868. bufferBytes *= 8192;
  1869. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1870. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1871. if ( stream_.deviceBuffer == NULL ) {
  1872. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  1873. goto error;
  1874. }
  1875. }
  1876. }
  1877. // Allocate memory for the Jack ports (channels) identifiers.
  1878. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  1879. if ( handle->ports[mode] == NULL ) {
  1880. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  1881. goto error;
  1882. }
  1883. stream_.device[mode] = device;
  1884. stream_.channelOffset[mode] = firstChannel;
  1885. stream_.state = STREAM_STOPPED;
  1886. stream_.callbackInfo.object = (void *) this;
  1887. if ( stream_.mode == OUTPUT && mode == INPUT )
  1888. // We had already set up the stream for output.
  1889. stream_.mode = DUPLEX;
  1890. else {
  1891. stream_.mode = mode;
  1892. jackbridge_set_buffer_size_callback( handle->client, jackBufferSizeHandler, (void *) &stream_.callbackInfo );
  1893. jackbridge_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  1894. jackbridge_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
  1895. jackbridge_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  1896. }
  1897. // Register our ports.
  1898. char label[64];
  1899. if ( mode == OUTPUT ) {
  1900. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1901. snprintf( label, 64, "audio-out%d", i+1 );
  1902. handle->ports[0][i] = jackbridge_port_register( handle->client, (const char *)label,
  1903. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  1904. }
  1905. }
  1906. else {
  1907. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1908. snprintf( label, 64, "audio-in%d", i+1 );
  1909. handle->ports[1][i] = jackbridge_port_register( handle->client, (const char *)label,
  1910. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  1911. }
  1912. }
  1913. // auto-connect "device" is #1
  1914. shouldAutoconnect_ = device == 0;
  1915. // Setup the buffer conversion information structure. We don't use
  1916. // buffers to do channel offsets, so we override that parameter
  1917. // here.
  1918. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  1919. if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
  1920. return SUCCESS;
  1921. error:
  1922. if ( handle ) {
  1923. pthread_cond_destroy( &handle->condition );
  1924. jackbridge_client_close( handle->client );
  1925. if ( handle->ports[0] ) free( handle->ports[0] );
  1926. if ( handle->ports[1] ) free( handle->ports[1] );
  1927. delete handle;
  1928. stream_.apiHandle = 0;
  1929. }
  1930. for ( int i=0; i<2; i++ ) {
  1931. if ( stream_.userBuffer[i] ) {
  1932. free( stream_.userBuffer[i] );
  1933. stream_.userBuffer[i] = 0;
  1934. }
  1935. }
  1936. if ( stream_.deviceBuffer ) {
  1937. free( stream_.deviceBuffer );
  1938. stream_.deviceBuffer = 0;
  1939. }
  1940. return FAILURE;
  1941. }
  1942. void RtApiJack :: closeStream( void )
  1943. {
  1944. if ( stream_.state == STREAM_CLOSED ) {
  1945. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  1946. error( RtAudioError::WARNING );
  1947. return;
  1948. }
  1949. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1950. if ( handle ) {
  1951. if ( stream_.state == STREAM_RUNNING )
  1952. jackbridge_deactivate( handle->client );
  1953. jackbridge_client_close( handle->client );
  1954. }
  1955. if ( handle ) {
  1956. if ( handle->ports[0] ) free( handle->ports[0] );
  1957. if ( handle->ports[1] ) free( handle->ports[1] );
  1958. pthread_cond_destroy( &handle->condition );
  1959. delete handle;
  1960. stream_.apiHandle = 0;
  1961. }
  1962. for ( int i=0; i<2; i++ ) {
  1963. if ( stream_.userBuffer[i] ) {
  1964. free( stream_.userBuffer[i] );
  1965. stream_.userBuffer[i] = 0;
  1966. }
  1967. }
  1968. if ( stream_.deviceBuffer ) {
  1969. free( stream_.deviceBuffer );
  1970. stream_.deviceBuffer = 0;
  1971. }
  1972. stream_.mode = UNINITIALIZED;
  1973. stream_.state = STREAM_CLOSED;
  1974. }
  1975. void RtApiJack :: startStream( void )
  1976. {
  1977. verifyStream();
  1978. if ( stream_.state == STREAM_RUNNING ) {
  1979. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  1980. error( RtAudioError::WARNING );
  1981. return;
  1982. }
  1983. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1984. bool result = jackbridge_activate( handle->client );
  1985. if ( ! result ) {
  1986. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  1987. goto unlock;
  1988. }
  1989. const char **ports;
  1990. // Get the list of available ports.
  1991. if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
  1992. result = false;
  1993. ports = jackbridge_get_ports( handle->client, "system:", NULL, JackPortIsInput);
  1994. if ( ports == NULL) {
  1995. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  1996. goto unlock;
  1997. }
  1998. // Now make the port connections. Since RtAudio wasn't designed to
  1999. // allow the user to select particular channels of a device, we'll
  2000. // just open the first "nChannels" ports with offset.
  2001. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2002. result = false;
  2003. if ( ports[ stream_.channelOffset[0] + i ] )
  2004. result = jackbridge_connect( handle->client, jackbridge_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2005. if ( ! result ) {
  2006. jackbridge_free( ports );
  2007. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2008. goto unlock;
  2009. }
  2010. }
  2011. jackbridge_free(ports);
  2012. }
  2013. if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
  2014. result = false;
  2015. ports = jackbridge_get_ports( handle->client, "system:", NULL, JackPortIsOutput );
  2016. if ( ports == NULL) {
  2017. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2018. goto unlock;
  2019. }
  2020. // Now make the port connections. See note above.
  2021. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2022. result = false;
  2023. if ( ports[ stream_.channelOffset[1] + i ] )
  2024. result = jackbridge_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jackbridge_port_name( handle->ports[1][i] ) );
  2025. if ( ! result ) {
  2026. jackbridge_free( ports );
  2027. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2028. goto unlock;
  2029. }
  2030. }
  2031. jackbridge_free(ports);
  2032. }
  2033. handle->drainCounter = 0;
  2034. handle->internalDrain = false;
  2035. stream_.state = STREAM_RUNNING;
  2036. unlock:
  2037. if ( result ) return;
  2038. error( RtAudioError::SYSTEM_ERROR );
  2039. }
  2040. void RtApiJack :: stopStream( void )
  2041. {
  2042. verifyStream();
  2043. if ( stream_.state == STREAM_STOPPED ) {
  2044. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2045. error( RtAudioError::WARNING );
  2046. return;
  2047. }
  2048. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2049. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2050. if ( handle->drainCounter == 0 ) {
  2051. handle->drainCounter = 2;
  2052. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2053. }
  2054. }
  2055. jackbridge_deactivate( handle->client );
  2056. stream_.state = STREAM_STOPPED;
  2057. }
  2058. void RtApiJack :: abortStream( void )
  2059. {
  2060. verifyStream();
  2061. if ( stream_.state == STREAM_STOPPED ) {
  2062. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2063. error( RtAudioError::WARNING );
  2064. return;
  2065. }
  2066. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2067. handle->drainCounter = 2;
  2068. stopStream();
  2069. }
  2070. // This function will be called by a spawned thread when the user
  2071. // callback function signals that the stream should be stopped or
  2072. // aborted. It is necessary to handle it this way because the
  2073. // callbackEvent() function must return before the jackbridge_deactivate()
  2074. // function will return.
  2075. static void *jackStopStream( void *ptr )
  2076. {
  2077. CallbackInfo *info = (CallbackInfo *) ptr;
  2078. RtApiJack *object = (RtApiJack *) info->object;
  2079. object->stopStream();
  2080. pthread_exit( NULL );
  2081. return NULL;
  2082. }
  2083. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2084. {
  2085. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2086. if ( stream_.state == STREAM_CLOSED ) {
  2087. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2088. error( RtAudioError::WARNING );
  2089. return FAILURE;
  2090. }
  2091. if ( nframes > 8192 ) {
  2092. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size is too big ... cannot process!";
  2093. error( RtAudioError::WARNING );
  2094. return FAILURE;
  2095. }
  2096. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2097. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2098. // Check if we were draining the stream and signal is finished.
  2099. if ( handle->drainCounter > 3 ) {
  2100. ThreadHandle threadId;
  2101. stream_.state = STREAM_STOPPING;
  2102. if ( handle->internalDrain == true )
  2103. pthread_create( &threadId, NULL, jackStopStream, info );
  2104. else
  2105. pthread_cond_signal( &handle->condition );
  2106. return SUCCESS;
  2107. }
  2108. // Invoke user callback first, to get fresh output data.
  2109. if ( handle->drainCounter == 0 ) {
  2110. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2111. double streamTime = getStreamTime();
  2112. RtAudioStreamStatus status = 0;
  2113. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2114. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2115. handle->xrun[0] = false;
  2116. }
  2117. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2118. status |= RTAUDIO_INPUT_OVERFLOW;
  2119. handle->xrun[1] = false;
  2120. }
  2121. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2122. nframes, streamTime, status, info->userData );
  2123. if ( cbReturnValue == 2 ) {
  2124. stream_.state = STREAM_STOPPING;
  2125. handle->drainCounter = 2;
  2126. ThreadHandle id;
  2127. pthread_create( &id, NULL, jackStopStream, info );
  2128. return SUCCESS;
  2129. }
  2130. else if ( cbReturnValue == 1 ) {
  2131. handle->drainCounter = 1;
  2132. handle->internalDrain = true;
  2133. }
  2134. }
  2135. jack_default_audio_sample_t *jackbuffer;
  2136. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2137. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2138. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2139. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2140. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2141. memset( jackbuffer, 0, bufferBytes );
  2142. }
  2143. }
  2144. else if ( stream_.doConvertBuffer[0] ) {
  2145. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2146. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2147. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2148. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2149. }
  2150. }
  2151. else { // no buffer conversion
  2152. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2153. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2154. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2155. }
  2156. }
  2157. }
  2158. // Don't bother draining input
  2159. if ( handle->drainCounter ) {
  2160. handle->drainCounter++;
  2161. goto unlock;
  2162. }
  2163. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2164. if ( stream_.doConvertBuffer[1] ) {
  2165. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2166. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2167. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2168. }
  2169. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2170. }
  2171. else { // no buffer conversion
  2172. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2173. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2174. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2175. }
  2176. }
  2177. }
  2178. unlock:
  2179. RtApi::tickStreamTime();
  2180. return SUCCESS;
  2181. }
  2182. bool RtApiJack :: bufferSizeEvent( unsigned long nframes )
  2183. {
  2184. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2185. if ( stream_.state == STREAM_CLOSED ) {
  2186. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2187. error( RtAudioError::WARNING );
  2188. return FAILURE;
  2189. }
  2190. if ( nframes > 8192 ) {
  2191. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size is too big ... cannot process!";
  2192. error( RtAudioError::WARNING );
  2193. return FAILURE;
  2194. }
  2195. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2196. RtAudioBufferSizeCallback callback = (RtAudioBufferSizeCallback) info->bufSizeCallback;
  2197. return callback( nframes, info->userData );
  2198. }
  2199. //******************** End of __UNIX_JACK__ *********************//
  2200. #endif
  2201. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2202. // The ASIO API is designed around a callback scheme, so this
  2203. // implementation is similar to that used for OS-X CoreAudio and Linux
  2204. // Jack. The primary constraint with ASIO is that it only allows
  2205. // access to a single driver at a time. Thus, it is not possible to
  2206. // have more than one simultaneous RtAudio stream.
  2207. //
  2208. // This implementation also requires a number of external ASIO files
  2209. // and a few global variables. The ASIO callback scheme does not
  2210. // allow for the passing of user data, so we must create a global
  2211. // pointer to our callbackInfo structure.
  2212. //
  2213. // On unix systems, we make use of a pthread condition variable.
  2214. // Since there is no equivalent in Windows, I hacked something based
  2215. // on information found in
  2216. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2217. #include "asio.cpp"
  2218. #include "asiodrivers.cpp"
  2219. #include "asiolist.cpp"
  2220. #include "iasiothiscallresolver.cpp"
  2221. #include <cmath>
  2222. static AsioDrivers drivers;
  2223. static ASIOCallbacks asioCallbacks;
  2224. static ASIODriverInfo driverInfo;
  2225. static CallbackInfo *asioCallbackInfo;
  2226. static bool asioXRun;
  2227. struct AsioHandle {
  2228. int drainCounter; // Tracks callback counts when draining
  2229. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2230. ASIOBufferInfo *bufferInfos;
  2231. HANDLE condition;
  2232. AsioHandle()
  2233. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2234. };
  2235. // Function declarations (definitions at end of section)
  2236. static const char* getAsioErrorString( ASIOError result );
  2237. static void sampleRateChanged( ASIOSampleRate sRate );
  2238. static long asioMessages( long selector, long value, void* message, double* opt );
  2239. RtApiAsio :: RtApiAsio()
  2240. {
  2241. // ASIO cannot run on a multi-threaded appartment. You can call
  2242. // CoInitialize beforehand, but it must be for appartment threading
  2243. // (in which case, CoInitilialize will return S_FALSE here).
  2244. coInitialized_ = false;
  2245. HRESULT hr = CoInitialize( NULL );
  2246. if ( FAILED(hr) ) {
  2247. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2248. error( RtAudioError::WARNING );
  2249. }
  2250. coInitialized_ = true;
  2251. drivers.removeCurrentDriver();
  2252. driverInfo.asioVersion = 2;
  2253. // See note in DirectSound implementation about GetDesktopWindow().
  2254. driverInfo.sysRef = GetForegroundWindow();
  2255. }
  2256. RtApiAsio :: ~RtApiAsio()
  2257. {
  2258. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2259. if ( coInitialized_ ) CoUninitialize();
  2260. }
  2261. unsigned int RtApiAsio :: getDeviceCount( void )
  2262. {
  2263. return (unsigned int) drivers.asioGetNumDev();
  2264. }
  2265. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2266. {
  2267. RtAudio::DeviceInfo info;
  2268. info.probed = false;
  2269. // Get device ID
  2270. unsigned int nDevices = getDeviceCount();
  2271. if ( nDevices == 0 ) {
  2272. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2273. error( RtAudioError::INVALID_USE );
  2274. return info;
  2275. }
  2276. if ( device >= nDevices ) {
  2277. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2278. error( RtAudioError::INVALID_USE );
  2279. return info;
  2280. }
  2281. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2282. if ( stream_.state != STREAM_CLOSED ) {
  2283. if ( device >= devices_.size() ) {
  2284. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2285. error( RtAudioError::WARNING );
  2286. return info;
  2287. }
  2288. return devices_[ device ];
  2289. }
  2290. char driverName[32];
  2291. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2292. if ( result != ASE_OK ) {
  2293. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2294. errorText_ = errorStream_.str();
  2295. error( RtAudioError::WARNING );
  2296. return info;
  2297. }
  2298. info.name = driverName;
  2299. if ( !drivers.loadDriver( driverName ) ) {
  2300. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2301. errorText_ = errorStream_.str();
  2302. error( RtAudioError::WARNING );
  2303. return info;
  2304. }
  2305. result = ASIOInit( &driverInfo );
  2306. if ( result != ASE_OK ) {
  2307. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2308. errorText_ = errorStream_.str();
  2309. error( RtAudioError::WARNING );
  2310. return info;
  2311. }
  2312. // Determine the device channel information.
  2313. long inputChannels, outputChannels;
  2314. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2315. if ( result != ASE_OK ) {
  2316. drivers.removeCurrentDriver();
  2317. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2318. errorText_ = errorStream_.str();
  2319. error( RtAudioError::WARNING );
  2320. return info;
  2321. }
  2322. info.outputChannels = outputChannels;
  2323. info.inputChannels = inputChannels;
  2324. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2325. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2326. // Determine the supported sample rates.
  2327. info.sampleRates.clear();
  2328. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2329. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2330. if ( result == ASE_OK ) {
  2331. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2332. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  2333. info.preferredSampleRate = SAMPLE_RATES[i];
  2334. }
  2335. }
  2336. // Determine supported data types ... just check first channel and assume rest are the same.
  2337. ASIOChannelInfo channelInfo;
  2338. channelInfo.channel = 0;
  2339. channelInfo.isInput = true;
  2340. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2341. result = ASIOGetChannelInfo( &channelInfo );
  2342. if ( result != ASE_OK ) {
  2343. drivers.removeCurrentDriver();
  2344. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2345. errorText_ = errorStream_.str();
  2346. error( RtAudioError::WARNING );
  2347. return info;
  2348. }
  2349. info.nativeFormats = 0;
  2350. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2351. info.nativeFormats |= RTAUDIO_SINT16;
  2352. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2353. info.nativeFormats |= RTAUDIO_SINT32;
  2354. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2355. info.nativeFormats |= RTAUDIO_FLOAT32;
  2356. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2357. info.nativeFormats |= RTAUDIO_FLOAT64;
  2358. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2359. info.nativeFormats |= RTAUDIO_SINT24;
  2360. if ( info.outputChannels > 0 )
  2361. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2362. if ( info.inputChannels > 0 )
  2363. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2364. info.probed = true;
  2365. drivers.removeCurrentDriver();
  2366. return info;
  2367. }
  2368. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2369. {
  2370. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2371. object->callbackEvent( index );
  2372. }
  2373. void RtApiAsio :: saveDeviceInfo( void )
  2374. {
  2375. devices_.clear();
  2376. unsigned int nDevices = getDeviceCount();
  2377. devices_.resize( nDevices );
  2378. for ( unsigned int i=0; i<nDevices; i++ )
  2379. devices_[i] = getDeviceInfo( i );
  2380. }
  2381. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2382. unsigned int firstChannel, unsigned int sampleRate,
  2383. RtAudioFormat format, unsigned int *bufferSize,
  2384. RtAudio::StreamOptions *options )
  2385. {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2386. bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
  2387. // For ASIO, a duplex stream MUST use the same driver.
  2388. if ( isDuplexInput && stream_.device[0] != device ) {
  2389. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2390. return FAILURE;
  2391. }
  2392. char driverName[32];
  2393. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2394. if ( result != ASE_OK ) {
  2395. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2396. errorText_ = errorStream_.str();
  2397. return FAILURE;
  2398. }
  2399. // Only load the driver once for duplex stream.
  2400. if ( !isDuplexInput ) {
  2401. // The getDeviceInfo() function will not work when a stream is open
  2402. // because ASIO does not allow multiple devices to run at the same
  2403. // time. Thus, we'll probe the system before opening a stream and
  2404. // save the results for use by getDeviceInfo().
  2405. this->saveDeviceInfo();
  2406. if ( !drivers.loadDriver( driverName ) ) {
  2407. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2408. errorText_ = errorStream_.str();
  2409. return FAILURE;
  2410. }
  2411. result = ASIOInit( &driverInfo );
  2412. if ( result != ASE_OK ) {
  2413. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2414. errorText_ = errorStream_.str();
  2415. return FAILURE;
  2416. }
  2417. }
  2418. // keep them before any "goto error", they are used for error cleanup + goto device boundary checks
  2419. bool buffersAllocated = false;
  2420. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2421. unsigned int nChannels;
  2422. // Check the device channel count.
  2423. long inputChannels, outputChannels;
  2424. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2425. if ( result != ASE_OK ) {
  2426. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2427. errorText_ = errorStream_.str();
  2428. goto error;
  2429. }
  2430. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2431. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2432. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2433. errorText_ = errorStream_.str();
  2434. goto error;
  2435. }
  2436. stream_.nDeviceChannels[mode] = channels;
  2437. stream_.nUserChannels[mode] = channels;
  2438. stream_.channelOffset[mode] = firstChannel;
  2439. // Verify the sample rate is supported.
  2440. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2441. if ( result != ASE_OK ) {
  2442. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2443. errorText_ = errorStream_.str();
  2444. goto error;
  2445. }
  2446. // Get the current sample rate
  2447. ASIOSampleRate currentRate;
  2448. result = ASIOGetSampleRate( &currentRate );
  2449. if ( result != ASE_OK ) {
  2450. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2451. errorText_ = errorStream_.str();
  2452. goto error;
  2453. }
  2454. // Set the sample rate only if necessary
  2455. if ( currentRate != sampleRate ) {
  2456. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2457. if ( result != ASE_OK ) {
  2458. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2459. errorText_ = errorStream_.str();
  2460. goto error;
  2461. }
  2462. }
  2463. // Determine the driver data type.
  2464. ASIOChannelInfo channelInfo;
  2465. channelInfo.channel = 0;
  2466. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2467. else channelInfo.isInput = true;
  2468. result = ASIOGetChannelInfo( &channelInfo );
  2469. if ( result != ASE_OK ) {
  2470. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2471. errorText_ = errorStream_.str();
  2472. goto error;
  2473. }
  2474. // Assuming WINDOWS host is always little-endian.
  2475. stream_.doByteSwap[mode] = false;
  2476. stream_.userFormat = format;
  2477. stream_.deviceFormat[mode] = 0;
  2478. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2479. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2480. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2481. }
  2482. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2483. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2484. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2485. }
  2486. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2487. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2488. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2489. }
  2490. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2491. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2492. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2493. }
  2494. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2495. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2496. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2497. }
  2498. if ( stream_.deviceFormat[mode] == 0 ) {
  2499. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2500. errorText_ = errorStream_.str();
  2501. goto error;
  2502. }
  2503. // Set the buffer size. For a duplex stream, this will end up
  2504. // setting the buffer size based on the input constraints, which
  2505. // should be ok.
  2506. long minSize, maxSize, preferSize, granularity;
  2507. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2508. if ( result != ASE_OK ) {
  2509. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2510. errorText_ = errorStream_.str();
  2511. goto error;
  2512. }
  2513. if ( isDuplexInput ) {
  2514. // When this is the duplex input (output was opened before), then we have to use the same
  2515. // buffersize as the output, because it might use the preferred buffer size, which most
  2516. // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
  2517. // So instead of throwing an error, make them equal. The caller uses the reference
  2518. // to the "bufferSize" param as usual to set up processing buffers.
  2519. *bufferSize = stream_.bufferSize;
  2520. } else {
  2521. if ( *bufferSize == 0 ) *bufferSize = preferSize;
  2522. else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2523. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2524. else if ( granularity == -1 ) {
  2525. // Make sure bufferSize is a power of two.
  2526. int log2_of_min_size = 0;
  2527. int log2_of_max_size = 0;
  2528. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2529. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2530. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2531. }
  2532. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2533. int min_delta_num = log2_of_min_size;
  2534. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2535. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2536. if (current_delta < min_delta) {
  2537. min_delta = current_delta;
  2538. min_delta_num = i;
  2539. }
  2540. }
  2541. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2542. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2543. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2544. }
  2545. else if ( granularity != 0 ) {
  2546. // Set to an even multiple of granularity, rounding up.
  2547. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2548. }
  2549. }
  2550. /*
  2551. // we don't use it anymore, see above!
  2552. // Just left it here for the case...
  2553. if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
  2554. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2555. goto error;
  2556. }
  2557. */
  2558. stream_.bufferSize = *bufferSize;
  2559. stream_.nBuffers = 2;
  2560. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2561. else stream_.userInterleaved = true;
  2562. // ASIO always uses non-interleaved buffers.
  2563. stream_.deviceInterleaved[mode] = false;
  2564. // Allocate, if necessary, our AsioHandle structure for the stream.
  2565. if ( handle == 0 ) {
  2566. try {
  2567. handle = new AsioHandle;
  2568. }
  2569. catch ( std::bad_alloc& ) {
  2570. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2571. goto error;
  2572. }
  2573. handle->bufferInfos = 0;
  2574. // Create a manual-reset event.
  2575. handle->condition = CreateEvent( NULL, // no security
  2576. TRUE, // manual-reset
  2577. FALSE, // non-signaled initially
  2578. NULL ); // unnamed
  2579. stream_.apiHandle = (void *) handle;
  2580. }
  2581. // Create the ASIO internal buffers. Since RtAudio sets up input
  2582. // and output separately, we'll have to dispose of previously
  2583. // created output buffers for a duplex stream.
  2584. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2585. ASIODisposeBuffers();
  2586. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2587. }
  2588. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2589. unsigned int i;
  2590. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2591. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2592. if ( handle->bufferInfos == NULL ) {
  2593. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2594. errorText_ = errorStream_.str();
  2595. goto error;
  2596. }
  2597. ASIOBufferInfo *infos;
  2598. infos = handle->bufferInfos;
  2599. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2600. infos->isInput = ASIOFalse;
  2601. infos->channelNum = i + stream_.channelOffset[0];
  2602. infos->buffers[0] = infos->buffers[1] = 0;
  2603. }
  2604. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2605. infos->isInput = ASIOTrue;
  2606. infos->channelNum = i + stream_.channelOffset[1];
  2607. infos->buffers[0] = infos->buffers[1] = 0;
  2608. }
  2609. // prepare for callbacks
  2610. stream_.sampleRate = sampleRate;
  2611. stream_.device[mode] = device;
  2612. stream_.mode = isDuplexInput ? DUPLEX : mode;
  2613. // store this class instance before registering callbacks, that are going to use it
  2614. asioCallbackInfo = &stream_.callbackInfo;
  2615. stream_.callbackInfo.object = (void *) this;
  2616. // Set up the ASIO callback structure and create the ASIO data buffers.
  2617. asioCallbacks.bufferSwitch = &bufferSwitch;
  2618. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2619. asioCallbacks.asioMessage = &asioMessages;
  2620. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2621. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2622. if ( result != ASE_OK ) {
  2623. // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
  2624. // but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver
  2625. // in that case, let's be naïve and try that instead
  2626. *bufferSize = preferSize;
  2627. stream_.bufferSize = *bufferSize;
  2628. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2629. }
  2630. if ( result != ASE_OK ) {
  2631. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2632. errorText_ = errorStream_.str();
  2633. goto error;
  2634. }
  2635. buffersAllocated = true;
  2636. stream_.state = STREAM_STOPPED;
  2637. // Set flags for buffer conversion.
  2638. stream_.doConvertBuffer[mode] = false;
  2639. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2640. stream_.doConvertBuffer[mode] = true;
  2641. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2642. stream_.nUserChannels[mode] > 1 )
  2643. stream_.doConvertBuffer[mode] = true;
  2644. // Allocate necessary internal buffers
  2645. unsigned long bufferBytes;
  2646. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2647. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2648. if ( stream_.userBuffer[mode] == NULL ) {
  2649. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2650. goto error;
  2651. }
  2652. if ( stream_.doConvertBuffer[mode] ) {
  2653. bool makeBuffer = true;
  2654. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2655. if ( isDuplexInput && stream_.deviceBuffer ) {
  2656. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2657. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2658. }
  2659. if ( makeBuffer ) {
  2660. bufferBytes *= *bufferSize;
  2661. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2662. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2663. if ( stream_.deviceBuffer == NULL ) {
  2664. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2665. goto error;
  2666. }
  2667. }
  2668. }
  2669. // Determine device latencies
  2670. long inputLatency, outputLatency;
  2671. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2672. if ( result != ASE_OK ) {
  2673. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2674. errorText_ = errorStream_.str();
  2675. error( RtAudioError::WARNING); // warn but don't fail
  2676. }
  2677. else {
  2678. stream_.latency[0] = outputLatency;
  2679. stream_.latency[1] = inputLatency;
  2680. }
  2681. // Setup the buffer conversion information structure. We don't use
  2682. // buffers to do channel offsets, so we override that parameter
  2683. // here.
  2684. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2685. return SUCCESS;
  2686. error:
  2687. if ( !isDuplexInput ) {
  2688. // the cleanup for error in the duplex input, is done by RtApi::openStream
  2689. // So we clean up for single channel only
  2690. if ( buffersAllocated )
  2691. ASIODisposeBuffers();
  2692. drivers.removeCurrentDriver();
  2693. if ( handle ) {
  2694. CloseHandle( handle->condition );
  2695. if ( handle->bufferInfos )
  2696. free( handle->bufferInfos );
  2697. delete handle;
  2698. stream_.apiHandle = 0;
  2699. }
  2700. if ( stream_.userBuffer[mode] ) {
  2701. free( stream_.userBuffer[mode] );
  2702. stream_.userBuffer[mode] = 0;
  2703. }
  2704. if ( stream_.deviceBuffer ) {
  2705. free( stream_.deviceBuffer );
  2706. stream_.deviceBuffer = 0;
  2707. }
  2708. }
  2709. return FAILURE;
  2710. }////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2711. void RtApiAsio :: closeStream()
  2712. {
  2713. if ( stream_.state == STREAM_CLOSED ) {
  2714. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2715. error( RtAudioError::WARNING );
  2716. return;
  2717. }
  2718. if ( stream_.state == STREAM_RUNNING ) {
  2719. stream_.state = STREAM_STOPPED;
  2720. ASIOStop();
  2721. }
  2722. ASIODisposeBuffers();
  2723. drivers.removeCurrentDriver();
  2724. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2725. if ( handle ) {
  2726. CloseHandle( handle->condition );
  2727. if ( handle->bufferInfos )
  2728. free( handle->bufferInfos );
  2729. delete handle;
  2730. stream_.apiHandle = 0;
  2731. }
  2732. for ( int i=0; i<2; i++ ) {
  2733. if ( stream_.userBuffer[i] ) {
  2734. free( stream_.userBuffer[i] );
  2735. stream_.userBuffer[i] = 0;
  2736. }
  2737. }
  2738. if ( stream_.deviceBuffer ) {
  2739. free( stream_.deviceBuffer );
  2740. stream_.deviceBuffer = 0;
  2741. }
  2742. stream_.mode = UNINITIALIZED;
  2743. stream_.state = STREAM_CLOSED;
  2744. }
  2745. bool stopThreadCalled = false;
  2746. void RtApiAsio :: startStream()
  2747. {
  2748. verifyStream();
  2749. if ( stream_.state == STREAM_RUNNING ) {
  2750. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2751. error( RtAudioError::WARNING );
  2752. return;
  2753. }
  2754. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2755. ASIOError result = ASIOStart();
  2756. if ( result != ASE_OK ) {
  2757. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2758. errorText_ = errorStream_.str();
  2759. goto unlock;
  2760. }
  2761. handle->drainCounter = 0;
  2762. handle->internalDrain = false;
  2763. ResetEvent( handle->condition );
  2764. stream_.state = STREAM_RUNNING;
  2765. asioXRun = false;
  2766. unlock:
  2767. stopThreadCalled = false;
  2768. if ( result == ASE_OK ) return;
  2769. error( RtAudioError::SYSTEM_ERROR );
  2770. }
  2771. void RtApiAsio :: stopStream()
  2772. {
  2773. verifyStream();
  2774. if ( stream_.state == STREAM_STOPPED ) {
  2775. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2776. error( RtAudioError::WARNING );
  2777. return;
  2778. }
  2779. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2780. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2781. if ( handle->drainCounter == 0 ) {
  2782. handle->drainCounter = 2;
  2783. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2784. }
  2785. }
  2786. stream_.state = STREAM_STOPPED;
  2787. ASIOError result = ASIOStop();
  2788. if ( result != ASE_OK ) {
  2789. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2790. errorText_ = errorStream_.str();
  2791. }
  2792. if ( result == ASE_OK ) return;
  2793. error( RtAudioError::SYSTEM_ERROR );
  2794. }
  2795. void RtApiAsio :: abortStream()
  2796. {
  2797. verifyStream();
  2798. if ( stream_.state == STREAM_STOPPED ) {
  2799. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2800. error( RtAudioError::WARNING );
  2801. return;
  2802. }
  2803. // The following lines were commented-out because some behavior was
  2804. // noted where the device buffers need to be zeroed to avoid
  2805. // continuing sound, even when the device buffers are completely
  2806. // disposed. So now, calling abort is the same as calling stop.
  2807. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2808. // handle->drainCounter = 2;
  2809. stopStream();
  2810. }
  2811. // This function will be called by a spawned thread when the user
  2812. // callback function signals that the stream should be stopped or
  2813. // aborted. It is necessary to handle it this way because the
  2814. // callbackEvent() function must return before the ASIOStop()
  2815. // function will return.
  2816. static unsigned __stdcall asioStopStream( void *ptr )
  2817. {
  2818. CallbackInfo *info = (CallbackInfo *) ptr;
  2819. RtApiAsio *object = (RtApiAsio *) info->object;
  2820. object->stopStream();
  2821. _endthreadex( 0 );
  2822. return 0;
  2823. }
  2824. bool RtApiAsio :: callbackEvent( long bufferIndex )
  2825. {
  2826. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2827. if ( stream_.state == STREAM_CLOSED ) {
  2828. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2829. error( RtAudioError::WARNING );
  2830. return FAILURE;
  2831. }
  2832. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2833. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2834. // Check if we were draining the stream and signal if finished.
  2835. if ( handle->drainCounter > 3 ) {
  2836. stream_.state = STREAM_STOPPING;
  2837. if ( handle->internalDrain == false )
  2838. SetEvent( handle->condition );
  2839. else { // spawn a thread to stop the stream
  2840. unsigned threadId;
  2841. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2842. &stream_.callbackInfo, 0, &threadId );
  2843. }
  2844. return SUCCESS;
  2845. }
  2846. // Invoke user callback to get fresh output data UNLESS we are
  2847. // draining stream.
  2848. if ( handle->drainCounter == 0 ) {
  2849. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2850. double streamTime = getStreamTime();
  2851. RtAudioStreamStatus status = 0;
  2852. if ( stream_.mode != INPUT && asioXRun == true ) {
  2853. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2854. asioXRun = false;
  2855. }
  2856. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  2857. status |= RTAUDIO_INPUT_OVERFLOW;
  2858. asioXRun = false;
  2859. }
  2860. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2861. stream_.bufferSize, streamTime, status, info->userData );
  2862. if ( cbReturnValue == 2 ) {
  2863. stream_.state = STREAM_STOPPING;
  2864. handle->drainCounter = 2;
  2865. unsigned threadId;
  2866. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2867. &stream_.callbackInfo, 0, &threadId );
  2868. return SUCCESS;
  2869. }
  2870. else if ( cbReturnValue == 1 ) {
  2871. handle->drainCounter = 1;
  2872. handle->internalDrain = true;
  2873. }
  2874. }
  2875. unsigned int nChannels, bufferBytes, i, j;
  2876. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2877. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2878. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  2879. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2880. for ( i=0, j=0; i<nChannels; i++ ) {
  2881. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2882. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  2883. }
  2884. }
  2885. else if ( stream_.doConvertBuffer[0] ) {
  2886. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2887. if ( stream_.doByteSwap[0] )
  2888. byteSwapBuffer( stream_.deviceBuffer,
  2889. stream_.bufferSize * stream_.nDeviceChannels[0],
  2890. stream_.deviceFormat[0] );
  2891. for ( i=0, j=0; i<nChannels; i++ ) {
  2892. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2893. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2894. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  2895. }
  2896. }
  2897. else {
  2898. if ( stream_.doByteSwap[0] )
  2899. byteSwapBuffer( stream_.userBuffer[0],
  2900. stream_.bufferSize * stream_.nUserChannels[0],
  2901. stream_.userFormat );
  2902. for ( i=0, j=0; i<nChannels; i++ ) {
  2903. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2904. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2905. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  2906. }
  2907. }
  2908. }
  2909. // Don't bother draining input
  2910. if ( handle->drainCounter ) {
  2911. handle->drainCounter++;
  2912. goto unlock;
  2913. }
  2914. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2915. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  2916. if (stream_.doConvertBuffer[1]) {
  2917. // Always interleave ASIO input data.
  2918. for ( i=0, j=0; i<nChannels; i++ ) {
  2919. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  2920. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  2921. handle->bufferInfos[i].buffers[bufferIndex],
  2922. bufferBytes );
  2923. }
  2924. if ( stream_.doByteSwap[1] )
  2925. byteSwapBuffer( stream_.deviceBuffer,
  2926. stream_.bufferSize * stream_.nDeviceChannels[1],
  2927. stream_.deviceFormat[1] );
  2928. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2929. }
  2930. else {
  2931. for ( i=0, j=0; i<nChannels; i++ ) {
  2932. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  2933. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  2934. handle->bufferInfos[i].buffers[bufferIndex],
  2935. bufferBytes );
  2936. }
  2937. }
  2938. if ( stream_.doByteSwap[1] )
  2939. byteSwapBuffer( stream_.userBuffer[1],
  2940. stream_.bufferSize * stream_.nUserChannels[1],
  2941. stream_.userFormat );
  2942. }
  2943. }
  2944. unlock:
  2945. // The following call was suggested by Malte Clasen. While the API
  2946. // documentation indicates it should not be required, some device
  2947. // drivers apparently do not function correctly without it.
  2948. ASIOOutputReady();
  2949. RtApi::tickStreamTime();
  2950. return SUCCESS;
  2951. }
  2952. static void sampleRateChanged( ASIOSampleRate sRate )
  2953. {
  2954. // The ASIO documentation says that this usually only happens during
  2955. // external sync. Audio processing is not stopped by the driver,
  2956. // actual sample rate might not have even changed, maybe only the
  2957. // sample rate status of an AES/EBU or S/PDIF digital input at the
  2958. // audio device.
  2959. RtApi *object = (RtApi *) asioCallbackInfo->object;
  2960. try {
  2961. object->stopStream();
  2962. }
  2963. catch ( RtAudioError &exception ) {
  2964. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  2965. return;
  2966. }
  2967. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  2968. }
  2969. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  2970. {
  2971. long ret = 0;
  2972. switch( selector ) {
  2973. case kAsioSelectorSupported:
  2974. if ( value == kAsioResetRequest
  2975. || value == kAsioEngineVersion
  2976. || value == kAsioResyncRequest
  2977. || value == kAsioLatenciesChanged
  2978. // The following three were added for ASIO 2.0, you don't
  2979. // necessarily have to support them.
  2980. || value == kAsioSupportsTimeInfo
  2981. || value == kAsioSupportsTimeCode
  2982. || value == kAsioSupportsInputMonitor)
  2983. ret = 1L;
  2984. break;
  2985. case kAsioResetRequest:
  2986. // Defer the task and perform the reset of the driver during the
  2987. // next "safe" situation. You cannot reset the driver right now,
  2988. // as this code is called from the driver. Reset the driver is
  2989. // done by completely destruct is. I.e. ASIOStop(),
  2990. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  2991. // driver again.
  2992. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  2993. ret = 1L;
  2994. break;
  2995. case kAsioResyncRequest:
  2996. // This informs the application that the driver encountered some
  2997. // non-fatal data loss. It is used for synchronization purposes
  2998. // of different media. Added mainly to work around the Win16Mutex
  2999. // problems in Windows 95/98 with the Windows Multimedia system,
  3000. // which could lose data because the Mutex was held too long by
  3001. // another thread. However a driver can issue it in other
  3002. // situations, too.
  3003. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3004. asioXRun = true;
  3005. ret = 1L;
  3006. break;
  3007. case kAsioLatenciesChanged:
  3008. // This will inform the host application that the drivers were
  3009. // latencies changed. Beware, it this does not mean that the
  3010. // buffer sizes have changed! You might need to update internal
  3011. // delay data.
  3012. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3013. ret = 1L;
  3014. break;
  3015. case kAsioEngineVersion:
  3016. // Return the supported ASIO version of the host application. If
  3017. // a host application does not implement this selector, ASIO 1.0
  3018. // is assumed by the driver.
  3019. ret = 2L;
  3020. break;
  3021. case kAsioSupportsTimeInfo:
  3022. // Informs the driver whether the
  3023. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3024. // For compatibility with ASIO 1.0 drivers the host application
  3025. // should always support the "old" bufferSwitch method, too.
  3026. ret = 0;
  3027. break;
  3028. case kAsioSupportsTimeCode:
  3029. // Informs the driver whether application is interested in time
  3030. // code info. If an application does not need to know about time
  3031. // code, the driver has less work to do.
  3032. ret = 0;
  3033. break;
  3034. }
  3035. return ret;
  3036. }
  3037. static const char* getAsioErrorString( ASIOError result )
  3038. {
  3039. struct Messages
  3040. {
  3041. ASIOError value;
  3042. const char*message;
  3043. };
  3044. static const Messages m[] =
  3045. {
  3046. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3047. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3048. { ASE_InvalidParameter, "Invalid input parameter." },
  3049. { ASE_InvalidMode, "Invalid mode." },
  3050. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3051. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3052. { ASE_NoMemory, "Not enough memory to complete the request." }
  3053. };
  3054. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3055. if ( m[i].value == result ) return m[i].message;
  3056. return "Unknown error.";
  3057. }
  3058. //******************** End of __WINDOWS_ASIO__ *********************//
  3059. #endif
  3060. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3061. // Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
  3062. // - Introduces support for the Windows WASAPI API
  3063. // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
  3064. // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
  3065. // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
  3066. #ifndef INITGUID
  3067. #define INITGUID
  3068. #endif
  3069. #include <audioclient.h>
  3070. #include <avrt.h>
  3071. #include <mmdeviceapi.h>
  3072. #include <functiondiscoverykeys_devpkey.h>
  3073. #include <sstream>
  3074. //=============================================================================
  3075. #define SAFE_RELEASE( objectPtr )\
  3076. if ( objectPtr )\
  3077. {\
  3078. objectPtr->Release();\
  3079. objectPtr = NULL;\
  3080. }
  3081. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3082. //-----------------------------------------------------------------------------
  3083. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3084. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3085. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3086. // provide intermediate storage for read / write synchronization.
  3087. class WasapiBuffer
  3088. {
  3089. public:
  3090. WasapiBuffer()
  3091. : buffer_( NULL ),
  3092. bufferSize_( 0 ),
  3093. inIndex_( 0 ),
  3094. outIndex_( 0 ) {}
  3095. ~WasapiBuffer() {
  3096. free( buffer_ );
  3097. }
  3098. // sets the length of the internal ring buffer
  3099. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3100. free( buffer_ );
  3101. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3102. bufferSize_ = bufferSize;
  3103. inIndex_ = 0;
  3104. outIndex_ = 0;
  3105. }
  3106. // attempt to push a buffer into the ring buffer at the current "in" index
  3107. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3108. {
  3109. if ( !buffer || // incoming buffer is NULL
  3110. bufferSize == 0 || // incoming buffer has no data
  3111. bufferSize > bufferSize_ ) // incoming buffer too large
  3112. {
  3113. return false;
  3114. }
  3115. unsigned int relOutIndex = outIndex_;
  3116. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3117. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3118. relOutIndex += bufferSize_;
  3119. }
  3120. // "in" index can end on the "out" index but cannot begin at it
  3121. if ( inIndex_ <= relOutIndex && inIndexEnd > relOutIndex ) {
  3122. return false; // not enough space between "in" index and "out" index
  3123. }
  3124. // copy buffer from external to internal
  3125. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3126. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3127. int fromInSize = bufferSize - fromZeroSize;
  3128. switch( format )
  3129. {
  3130. case RTAUDIO_SINT8:
  3131. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3132. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3133. break;
  3134. case RTAUDIO_SINT16:
  3135. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3136. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3137. break;
  3138. case RTAUDIO_SINT24:
  3139. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3140. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3141. break;
  3142. case RTAUDIO_SINT32:
  3143. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3144. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3145. break;
  3146. case RTAUDIO_FLOAT32:
  3147. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3148. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3149. break;
  3150. case RTAUDIO_FLOAT64:
  3151. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3152. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3153. break;
  3154. }
  3155. // update "in" index
  3156. inIndex_ += bufferSize;
  3157. inIndex_ %= bufferSize_;
  3158. return true;
  3159. }
  3160. // attempt to pull a buffer from the ring buffer from the current "out" index
  3161. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3162. {
  3163. if ( !buffer || // incoming buffer is NULL
  3164. bufferSize == 0 || // incoming buffer has no data
  3165. bufferSize > bufferSize_ ) // incoming buffer too large
  3166. {
  3167. return false;
  3168. }
  3169. unsigned int relInIndex = inIndex_;
  3170. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3171. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3172. relInIndex += bufferSize_;
  3173. }
  3174. // "out" index can begin at and end on the "in" index
  3175. if ( outIndex_ < relInIndex && outIndexEnd > relInIndex ) {
  3176. return false; // not enough space between "out" index and "in" index
  3177. }
  3178. // copy buffer from internal to external
  3179. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3180. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3181. int fromOutSize = bufferSize - fromZeroSize;
  3182. switch( format )
  3183. {
  3184. case RTAUDIO_SINT8:
  3185. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3186. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3187. break;
  3188. case RTAUDIO_SINT16:
  3189. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3190. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3191. break;
  3192. case RTAUDIO_SINT24:
  3193. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3194. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3195. break;
  3196. case RTAUDIO_SINT32:
  3197. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3198. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3199. break;
  3200. case RTAUDIO_FLOAT32:
  3201. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3202. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3203. break;
  3204. case RTAUDIO_FLOAT64:
  3205. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3206. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3207. break;
  3208. }
  3209. // update "out" index
  3210. outIndex_ += bufferSize;
  3211. outIndex_ %= bufferSize_;
  3212. return true;
  3213. }
  3214. private:
  3215. char* buffer_;
  3216. unsigned int bufferSize_;
  3217. unsigned int inIndex_;
  3218. unsigned int outIndex_;
  3219. };
  3220. //-----------------------------------------------------------------------------
  3221. // A structure to hold various information related to the WASAPI implementation.
  3222. struct WasapiHandle
  3223. {
  3224. IAudioClient* captureAudioClient;
  3225. IAudioClient* renderAudioClient;
  3226. IAudioCaptureClient* captureClient;
  3227. IAudioRenderClient* renderClient;
  3228. HANDLE captureEvent;
  3229. HANDLE renderEvent;
  3230. WasapiHandle()
  3231. : captureAudioClient( NULL ),
  3232. renderAudioClient( NULL ),
  3233. captureClient( NULL ),
  3234. renderClient( NULL ),
  3235. captureEvent( NULL ),
  3236. renderEvent( NULL ) {}
  3237. };
  3238. //=============================================================================
  3239. RtApiWasapi::RtApiWasapi()
  3240. : coInitialized_( false ), deviceEnumerator_( NULL )
  3241. {
  3242. // WASAPI can run either apartment or multi-threaded
  3243. HRESULT hr = CoInitialize( NULL );
  3244. if ( !FAILED( hr ) )
  3245. coInitialized_ = true;
  3246. // Instantiate device enumerator
  3247. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3248. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3249. ( void** ) &deviceEnumerator_ );
  3250. if ( FAILED( hr ) ) {
  3251. errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";
  3252. error( RtAudioError::DRIVER_ERROR );
  3253. }
  3254. }
  3255. //-----------------------------------------------------------------------------
  3256. RtApiWasapi::~RtApiWasapi()
  3257. {
  3258. if ( stream_.state != STREAM_CLOSED )
  3259. closeStream();
  3260. SAFE_RELEASE( deviceEnumerator_ );
  3261. // If this object previously called CoInitialize()
  3262. if ( coInitialized_ )
  3263. CoUninitialize();
  3264. }
  3265. //=============================================================================
  3266. unsigned int RtApiWasapi::getDeviceCount( void )
  3267. {
  3268. unsigned int captureDeviceCount = 0;
  3269. unsigned int renderDeviceCount = 0;
  3270. IMMDeviceCollection* captureDevices = NULL;
  3271. IMMDeviceCollection* renderDevices = NULL;
  3272. // Count capture devices
  3273. errorText_.clear();
  3274. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3275. if ( FAILED( hr ) ) {
  3276. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3277. goto Exit;
  3278. }
  3279. hr = captureDevices->GetCount( &captureDeviceCount );
  3280. if ( FAILED( hr ) ) {
  3281. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3282. goto Exit;
  3283. }
  3284. // Count render devices
  3285. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3286. if ( FAILED( hr ) ) {
  3287. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3288. goto Exit;
  3289. }
  3290. hr = renderDevices->GetCount( &renderDeviceCount );
  3291. if ( FAILED( hr ) ) {
  3292. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3293. goto Exit;
  3294. }
  3295. Exit:
  3296. // release all references
  3297. SAFE_RELEASE( captureDevices );
  3298. SAFE_RELEASE( renderDevices );
  3299. if ( errorText_.empty() )
  3300. return captureDeviceCount + renderDeviceCount;
  3301. error( RtAudioError::DRIVER_ERROR );
  3302. return 0;
  3303. }
  3304. //-----------------------------------------------------------------------------
  3305. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3306. {
  3307. RtAudio::DeviceInfo info;
  3308. unsigned int captureDeviceCount = 0;
  3309. unsigned int renderDeviceCount = 0;
  3310. std::string defaultDeviceName;
  3311. bool isCaptureDevice = false;
  3312. PROPVARIANT deviceNameProp;
  3313. PROPVARIANT defaultDeviceNameProp;
  3314. IMMDeviceCollection* captureDevices = NULL;
  3315. IMMDeviceCollection* renderDevices = NULL;
  3316. IMMDevice* devicePtr = NULL;
  3317. IMMDevice* defaultDevicePtr = NULL;
  3318. IAudioClient* audioClient = NULL;
  3319. IPropertyStore* devicePropStore = NULL;
  3320. IPropertyStore* defaultDevicePropStore = NULL;
  3321. WAVEFORMATEX* deviceFormat = NULL;
  3322. WAVEFORMATEX* closestMatchFormat = NULL;
  3323. // probed
  3324. info.probed = false;
  3325. // Count capture devices
  3326. errorText_.clear();
  3327. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3328. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3329. if ( FAILED( hr ) ) {
  3330. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3331. goto Exit;
  3332. }
  3333. hr = captureDevices->GetCount( &captureDeviceCount );
  3334. if ( FAILED( hr ) ) {
  3335. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3336. goto Exit;
  3337. }
  3338. // Count render devices
  3339. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3340. if ( FAILED( hr ) ) {
  3341. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3342. goto Exit;
  3343. }
  3344. hr = renderDevices->GetCount( &renderDeviceCount );
  3345. if ( FAILED( hr ) ) {
  3346. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3347. goto Exit;
  3348. }
  3349. // validate device index
  3350. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3351. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3352. errorType = RtAudioError::INVALID_USE;
  3353. goto Exit;
  3354. }
  3355. // determine whether index falls within capture or render devices
  3356. if ( device >= renderDeviceCount ) {
  3357. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3358. if ( FAILED( hr ) ) {
  3359. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3360. goto Exit;
  3361. }
  3362. isCaptureDevice = true;
  3363. }
  3364. else {
  3365. hr = renderDevices->Item( device, &devicePtr );
  3366. if ( FAILED( hr ) ) {
  3367. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3368. goto Exit;
  3369. }
  3370. isCaptureDevice = false;
  3371. }
  3372. // get default device name
  3373. if ( isCaptureDevice ) {
  3374. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3375. if ( FAILED( hr ) ) {
  3376. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3377. goto Exit;
  3378. }
  3379. }
  3380. else {
  3381. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3382. if ( FAILED( hr ) ) {
  3383. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3384. goto Exit;
  3385. }
  3386. }
  3387. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3388. if ( FAILED( hr ) ) {
  3389. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3390. goto Exit;
  3391. }
  3392. PropVariantInit( &defaultDeviceNameProp );
  3393. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3394. if ( FAILED( hr ) ) {
  3395. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3396. goto Exit;
  3397. }
  3398. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3399. // name
  3400. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3401. if ( FAILED( hr ) ) {
  3402. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3403. goto Exit;
  3404. }
  3405. PropVariantInit( &deviceNameProp );
  3406. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3407. if ( FAILED( hr ) ) {
  3408. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3409. goto Exit;
  3410. }
  3411. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3412. // is default
  3413. if ( isCaptureDevice ) {
  3414. info.isDefaultInput = info.name == defaultDeviceName;
  3415. info.isDefaultOutput = false;
  3416. }
  3417. else {
  3418. info.isDefaultInput = false;
  3419. info.isDefaultOutput = info.name == defaultDeviceName;
  3420. }
  3421. // channel count
  3422. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3423. if ( FAILED( hr ) ) {
  3424. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3425. goto Exit;
  3426. }
  3427. hr = audioClient->GetMixFormat( &deviceFormat );
  3428. if ( FAILED( hr ) ) {
  3429. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3430. goto Exit;
  3431. }
  3432. if ( isCaptureDevice ) {
  3433. info.inputChannels = deviceFormat->nChannels;
  3434. info.outputChannels = 0;
  3435. info.duplexChannels = 0;
  3436. }
  3437. else {
  3438. info.inputChannels = 0;
  3439. info.outputChannels = deviceFormat->nChannels;
  3440. info.duplexChannels = 0;
  3441. }
  3442. // sample rates (WASAPI only supports the one native sample rate)
  3443. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3444. info.sampleRates.clear();
  3445. info.sampleRates.push_back( deviceFormat->nSamplesPerSec );
  3446. // native format
  3447. info.nativeFormats = 0;
  3448. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3449. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3450. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3451. {
  3452. if ( deviceFormat->wBitsPerSample == 32 ) {
  3453. info.nativeFormats |= RTAUDIO_FLOAT32;
  3454. }
  3455. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3456. info.nativeFormats |= RTAUDIO_FLOAT64;
  3457. }
  3458. }
  3459. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3460. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3461. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3462. {
  3463. if ( deviceFormat->wBitsPerSample == 8 ) {
  3464. info.nativeFormats |= RTAUDIO_SINT8;
  3465. }
  3466. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3467. info.nativeFormats |= RTAUDIO_SINT16;
  3468. }
  3469. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3470. info.nativeFormats |= RTAUDIO_SINT24;
  3471. }
  3472. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3473. info.nativeFormats |= RTAUDIO_SINT32;
  3474. }
  3475. }
  3476. // probed
  3477. info.probed = true;
  3478. Exit:
  3479. // release all references
  3480. PropVariantClear( &deviceNameProp );
  3481. PropVariantClear( &defaultDeviceNameProp );
  3482. SAFE_RELEASE( captureDevices );
  3483. SAFE_RELEASE( renderDevices );
  3484. SAFE_RELEASE( devicePtr );
  3485. SAFE_RELEASE( defaultDevicePtr );
  3486. SAFE_RELEASE( audioClient );
  3487. SAFE_RELEASE( devicePropStore );
  3488. SAFE_RELEASE( defaultDevicePropStore );
  3489. CoTaskMemFree( deviceFormat );
  3490. CoTaskMemFree( closestMatchFormat );
  3491. if ( !errorText_.empty() )
  3492. error( errorType );
  3493. return info;
  3494. }
  3495. //-----------------------------------------------------------------------------
  3496. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3497. {
  3498. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3499. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3500. return i;
  3501. }
  3502. }
  3503. return 0;
  3504. }
  3505. //-----------------------------------------------------------------------------
  3506. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3507. {
  3508. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3509. if ( getDeviceInfo( i ).isDefaultInput ) {
  3510. return i;
  3511. }
  3512. }
  3513. return 0;
  3514. }
  3515. //-----------------------------------------------------------------------------
  3516. void RtApiWasapi::closeStream( void )
  3517. {
  3518. if ( stream_.state == STREAM_CLOSED ) {
  3519. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3520. error( RtAudioError::WARNING );
  3521. return;
  3522. }
  3523. if ( stream_.state != STREAM_STOPPED )
  3524. stopStream();
  3525. // clean up stream memory
  3526. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3527. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3528. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3529. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3530. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3531. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3532. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3533. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3534. delete ( WasapiHandle* ) stream_.apiHandle;
  3535. stream_.apiHandle = NULL;
  3536. for ( int i = 0; i < 2; i++ ) {
  3537. if ( stream_.userBuffer[i] ) {
  3538. free( stream_.userBuffer[i] );
  3539. stream_.userBuffer[i] = 0;
  3540. }
  3541. }
  3542. if ( stream_.deviceBuffer ) {
  3543. free( stream_.deviceBuffer );
  3544. stream_.deviceBuffer = 0;
  3545. }
  3546. // update stream state
  3547. stream_.state = STREAM_CLOSED;
  3548. }
  3549. //-----------------------------------------------------------------------------
  3550. void RtApiWasapi::startStream( void )
  3551. {
  3552. verifyStream();
  3553. if ( stream_.state == STREAM_RUNNING ) {
  3554. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3555. error( RtAudioError::WARNING );
  3556. return;
  3557. }
  3558. // update stream state
  3559. stream_.state = STREAM_RUNNING;
  3560. // create WASAPI stream thread
  3561. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3562. if ( !stream_.callbackInfo.thread ) {
  3563. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3564. error( RtAudioError::THREAD_ERROR );
  3565. }
  3566. else {
  3567. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3568. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3569. }
  3570. }
  3571. //-----------------------------------------------------------------------------
  3572. void RtApiWasapi::stopStream( void )
  3573. {
  3574. verifyStream();
  3575. if ( stream_.state == STREAM_STOPPED ) {
  3576. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3577. error( RtAudioError::WARNING );
  3578. return;
  3579. }
  3580. // inform stream thread by setting stream state to STREAM_STOPPING
  3581. stream_.state = STREAM_STOPPING;
  3582. // wait until stream thread is stopped
  3583. while( stream_.state != STREAM_STOPPED ) {
  3584. Sleep( 1 );
  3585. }
  3586. // Wait for the last buffer to play before stopping.
  3587. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3588. // stop capture client if applicable
  3589. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3590. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3591. if ( FAILED( hr ) ) {
  3592. errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";
  3593. error( RtAudioError::DRIVER_ERROR );
  3594. return;
  3595. }
  3596. }
  3597. // stop render client if applicable
  3598. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3599. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3600. if ( FAILED( hr ) ) {
  3601. errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";
  3602. error( RtAudioError::DRIVER_ERROR );
  3603. return;
  3604. }
  3605. }
  3606. // close thread handle
  3607. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3608. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3609. error( RtAudioError::THREAD_ERROR );
  3610. return;
  3611. }
  3612. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3613. }
  3614. //-----------------------------------------------------------------------------
  3615. void RtApiWasapi::abortStream( void )
  3616. {
  3617. verifyStream();
  3618. if ( stream_.state == STREAM_STOPPED ) {
  3619. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3620. error( RtAudioError::WARNING );
  3621. return;
  3622. }
  3623. // inform stream thread by setting stream state to STREAM_STOPPING
  3624. stream_.state = STREAM_STOPPING;
  3625. // wait until stream thread is stopped
  3626. while ( stream_.state != STREAM_STOPPED ) {
  3627. Sleep( 1 );
  3628. }
  3629. // stop capture client if applicable
  3630. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3631. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3632. if ( FAILED( hr ) ) {
  3633. errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";
  3634. error( RtAudioError::DRIVER_ERROR );
  3635. return;
  3636. }
  3637. }
  3638. // stop render client if applicable
  3639. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3640. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3641. if ( FAILED( hr ) ) {
  3642. errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";
  3643. error( RtAudioError::DRIVER_ERROR );
  3644. return;
  3645. }
  3646. }
  3647. // close thread handle
  3648. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3649. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3650. error( RtAudioError::THREAD_ERROR );
  3651. return;
  3652. }
  3653. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3654. }
  3655. //-----------------------------------------------------------------------------
  3656. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3657. unsigned int firstChannel, unsigned int sampleRate,
  3658. RtAudioFormat format, unsigned int* bufferSize,
  3659. RtAudio::StreamOptions* options )
  3660. {
  3661. bool methodResult = FAILURE;
  3662. unsigned int captureDeviceCount = 0;
  3663. unsigned int renderDeviceCount = 0;
  3664. IMMDeviceCollection* captureDevices = NULL;
  3665. IMMDeviceCollection* renderDevices = NULL;
  3666. IMMDevice* devicePtr = NULL;
  3667. WAVEFORMATEX* deviceFormat = NULL;
  3668. unsigned int bufferBytes;
  3669. stream_.state = STREAM_STOPPED;
  3670. RtAudio::DeviceInfo deviceInfo;
  3671. // create API Handle if not already created
  3672. if ( !stream_.apiHandle )
  3673. stream_.apiHandle = ( void* ) new WasapiHandle();
  3674. // Count capture devices
  3675. errorText_.clear();
  3676. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3677. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3678. if ( FAILED( hr ) ) {
  3679. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  3680. goto Exit;
  3681. }
  3682. hr = captureDevices->GetCount( &captureDeviceCount );
  3683. if ( FAILED( hr ) ) {
  3684. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  3685. goto Exit;
  3686. }
  3687. // Count render devices
  3688. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3689. if ( FAILED( hr ) ) {
  3690. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  3691. goto Exit;
  3692. }
  3693. hr = renderDevices->GetCount( &renderDeviceCount );
  3694. if ( FAILED( hr ) ) {
  3695. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  3696. goto Exit;
  3697. }
  3698. // validate device index
  3699. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3700. errorType = RtAudioError::INVALID_USE;
  3701. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  3702. goto Exit;
  3703. }
  3704. deviceInfo = getDeviceInfo( device );
  3705. // validate sample rate
  3706. if ( sampleRate != deviceInfo.preferredSampleRate )
  3707. {
  3708. errorType = RtAudioError::INVALID_USE;
  3709. std::stringstream ss;
  3710. ss << "RtApiWasapi::probeDeviceOpen: " << sampleRate
  3711. << "Hz sample rate not supported. This device only supports "
  3712. << deviceInfo.preferredSampleRate << "Hz.";
  3713. errorText_ = ss.str();
  3714. goto Exit;
  3715. }
  3716. // determine whether index falls within capture or render devices
  3717. if ( device >= renderDeviceCount ) {
  3718. if ( mode != INPUT ) {
  3719. errorType = RtAudioError::INVALID_USE;
  3720. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  3721. goto Exit;
  3722. }
  3723. // retrieve captureAudioClient from devicePtr
  3724. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3725. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3726. if ( FAILED( hr ) ) {
  3727. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  3728. goto Exit;
  3729. }
  3730. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3731. NULL, ( void** ) &captureAudioClient );
  3732. if ( FAILED( hr ) ) {
  3733. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3734. goto Exit;
  3735. }
  3736. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  3737. if ( FAILED( hr ) ) {
  3738. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3739. goto Exit;
  3740. }
  3741. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3742. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3743. }
  3744. else {
  3745. if ( mode != OUTPUT ) {
  3746. errorType = RtAudioError::INVALID_USE;
  3747. errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";
  3748. goto Exit;
  3749. }
  3750. // retrieve renderAudioClient from devicePtr
  3751. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3752. hr = renderDevices->Item( device, &devicePtr );
  3753. if ( FAILED( hr ) ) {
  3754. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  3755. goto Exit;
  3756. }
  3757. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3758. NULL, ( void** ) &renderAudioClient );
  3759. if ( FAILED( hr ) ) {
  3760. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3761. goto Exit;
  3762. }
  3763. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  3764. if ( FAILED( hr ) ) {
  3765. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3766. goto Exit;
  3767. }
  3768. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3769. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3770. }
  3771. // fill stream data
  3772. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  3773. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  3774. stream_.mode = DUPLEX;
  3775. }
  3776. else {
  3777. stream_.mode = mode;
  3778. }
  3779. stream_.device[mode] = device;
  3780. stream_.doByteSwap[mode] = false;
  3781. stream_.sampleRate = sampleRate;
  3782. stream_.bufferSize = *bufferSize;
  3783. stream_.nBuffers = 1;
  3784. stream_.nUserChannels[mode] = channels;
  3785. stream_.channelOffset[mode] = firstChannel;
  3786. stream_.userFormat = format;
  3787. stream_.deviceFormat[mode] = deviceInfo.nativeFormats;
  3788. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  3789. stream_.userInterleaved = false;
  3790. else
  3791. stream_.userInterleaved = true;
  3792. stream_.deviceInterleaved[mode] = true;
  3793. // Set flags for buffer conversion.
  3794. stream_.doConvertBuffer[mode] = false;
  3795. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  3796. stream_.nUserChannels != stream_.nDeviceChannels )
  3797. stream_.doConvertBuffer[mode] = true;
  3798. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  3799. stream_.nUserChannels[mode] > 1 )
  3800. stream_.doConvertBuffer[mode] = true;
  3801. if ( stream_.doConvertBuffer[mode] )
  3802. setConvertInfo( mode, 0 );
  3803. // Allocate necessary internal buffers
  3804. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  3805. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  3806. if ( !stream_.userBuffer[mode] ) {
  3807. errorType = RtAudioError::MEMORY_ERROR;
  3808. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  3809. goto Exit;
  3810. }
  3811. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  3812. stream_.callbackInfo.priority = 15;
  3813. else
  3814. stream_.callbackInfo.priority = 0;
  3815. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  3816. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  3817. methodResult = SUCCESS;
  3818. Exit:
  3819. //clean up
  3820. SAFE_RELEASE( captureDevices );
  3821. SAFE_RELEASE( renderDevices );
  3822. SAFE_RELEASE( devicePtr );
  3823. CoTaskMemFree( deviceFormat );
  3824. // if method failed, close the stream
  3825. if ( methodResult == FAILURE )
  3826. closeStream();
  3827. if ( !errorText_.empty() )
  3828. error( errorType );
  3829. return methodResult;
  3830. }
  3831. //=============================================================================
  3832. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  3833. {
  3834. if ( wasapiPtr )
  3835. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  3836. return 0;
  3837. }
  3838. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  3839. {
  3840. if ( wasapiPtr )
  3841. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  3842. return 0;
  3843. }
  3844. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  3845. {
  3846. if ( wasapiPtr )
  3847. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  3848. return 0;
  3849. }
  3850. //-----------------------------------------------------------------------------
  3851. void RtApiWasapi::wasapiThread()
  3852. {
  3853. // as this is a new thread, we must CoInitialize it
  3854. CoInitialize( NULL );
  3855. HRESULT hr;
  3856. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3857. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3858. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  3859. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  3860. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  3861. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  3862. WAVEFORMATEX* captureFormat = NULL;
  3863. WAVEFORMATEX* renderFormat = NULL;
  3864. WasapiBuffer captureBuffer;
  3865. WasapiBuffer renderBuffer;
  3866. // declare local stream variables
  3867. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  3868. BYTE* streamBuffer = NULL;
  3869. unsigned long captureFlags = 0;
  3870. unsigned int bufferFrameCount = 0;
  3871. unsigned int numFramesPadding = 0;
  3872. bool callbackPushed = false;
  3873. bool callbackPulled = false;
  3874. bool callbackStopped = false;
  3875. int callbackResult = 0;
  3876. unsigned int deviceBuffSize = 0;
  3877. errorText_.clear();
  3878. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3879. // Attempt to assign "Pro Audio" characteristic to thread
  3880. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  3881. if ( AvrtDll ) {
  3882. DWORD taskIndex = 0;
  3883. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  3884. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  3885. FreeLibrary( AvrtDll );
  3886. }
  3887. // start capture stream if applicable
  3888. if ( captureAudioClient ) {
  3889. hr = captureAudioClient->GetMixFormat( &captureFormat );
  3890. if ( FAILED( hr ) ) {
  3891. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  3892. goto Exit;
  3893. }
  3894. // initialize capture stream according to desire buffer size
  3895. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) stream_.bufferSize * 10000000 / captureFormat->nSamplesPerSec );
  3896. if ( !captureClient ) {
  3897. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  3898. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  3899. desiredBufferPeriod,
  3900. desiredBufferPeriod,
  3901. captureFormat,
  3902. NULL );
  3903. if ( FAILED( hr ) ) {
  3904. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  3905. goto Exit;
  3906. }
  3907. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  3908. ( void** ) &captureClient );
  3909. if ( FAILED( hr ) ) {
  3910. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  3911. goto Exit;
  3912. }
  3913. // configure captureEvent to trigger on every available capture buffer
  3914. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  3915. if ( !captureEvent ) {
  3916. errorType = RtAudioError::SYSTEM_ERROR;
  3917. errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  3918. goto Exit;
  3919. }
  3920. hr = captureAudioClient->SetEventHandle( captureEvent );
  3921. if ( FAILED( hr ) ) {
  3922. errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  3923. goto Exit;
  3924. }
  3925. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  3926. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  3927. }
  3928. unsigned int inBufferSize = 0;
  3929. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  3930. if ( FAILED( hr ) ) {
  3931. errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  3932. goto Exit;
  3933. }
  3934. // scale outBufferSize according to stream->user sample rate ratio
  3935. unsigned int outBufferSize = ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[INPUT];
  3936. inBufferSize *= stream_.nDeviceChannels[INPUT];
  3937. // set captureBuffer size
  3938. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  3939. // reset the capture stream
  3940. hr = captureAudioClient->Reset();
  3941. if ( FAILED( hr ) ) {
  3942. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  3943. goto Exit;
  3944. }
  3945. // start the capture stream
  3946. hr = captureAudioClient->Start();
  3947. if ( FAILED( hr ) ) {
  3948. errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  3949. goto Exit;
  3950. }
  3951. }
  3952. // start render stream if applicable
  3953. if ( renderAudioClient ) {
  3954. hr = renderAudioClient->GetMixFormat( &renderFormat );
  3955. if ( FAILED( hr ) ) {
  3956. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  3957. goto Exit;
  3958. }
  3959. // initialize render stream according to desire buffer size
  3960. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) stream_.bufferSize * 10000000 / renderFormat->nSamplesPerSec );
  3961. if ( !renderClient ) {
  3962. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  3963. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  3964. desiredBufferPeriod,
  3965. desiredBufferPeriod,
  3966. renderFormat,
  3967. NULL );
  3968. if ( FAILED( hr ) ) {
  3969. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  3970. goto Exit;
  3971. }
  3972. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  3973. ( void** ) &renderClient );
  3974. if ( FAILED( hr ) ) {
  3975. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  3976. goto Exit;
  3977. }
  3978. // configure renderEvent to trigger on every available render buffer
  3979. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  3980. if ( !renderEvent ) {
  3981. errorType = RtAudioError::SYSTEM_ERROR;
  3982. errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";
  3983. goto Exit;
  3984. }
  3985. hr = renderAudioClient->SetEventHandle( renderEvent );
  3986. if ( FAILED( hr ) ) {
  3987. errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  3988. goto Exit;
  3989. }
  3990. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  3991. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  3992. }
  3993. unsigned int outBufferSize = 0;
  3994. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  3995. if ( FAILED( hr ) ) {
  3996. errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  3997. goto Exit;
  3998. }
  3999. // scale inBufferSize according to user->stream sample rate ratio
  4000. unsigned int inBufferSize = ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[OUTPUT];
  4001. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4002. // set renderBuffer size
  4003. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4004. // reset the render stream
  4005. hr = renderAudioClient->Reset();
  4006. if ( FAILED( hr ) ) {
  4007. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4008. goto Exit;
  4009. }
  4010. // start the render stream
  4011. hr = renderAudioClient->Start();
  4012. if ( FAILED( hr ) ) {
  4013. errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4014. goto Exit;
  4015. }
  4016. }
  4017. if ( stream_.mode == INPUT ) {
  4018. using namespace std; // for roundf
  4019. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4020. }
  4021. else if ( stream_.mode == OUTPUT ) {
  4022. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4023. }
  4024. else if ( stream_.mode == DUPLEX ) {
  4025. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4026. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4027. }
  4028. stream_.deviceBuffer = ( char* ) malloc( deviceBuffSize );
  4029. if ( !stream_.deviceBuffer ) {
  4030. errorType = RtAudioError::MEMORY_ERROR;
  4031. errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4032. goto Exit;
  4033. }
  4034. // stream process loop
  4035. while ( stream_.state != STREAM_STOPPING ) {
  4036. if ( !callbackPulled ) {
  4037. // Callback Input
  4038. // ==============
  4039. // 1. Pull callback buffer from inputBuffer
  4040. // 2. If 1. was successful: Convert callback buffer to user format
  4041. if ( captureAudioClient ) {
  4042. // Pull callback buffer from inputBuffer
  4043. callbackPulled = captureBuffer.pullBuffer( stream_.deviceBuffer,
  4044. ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[INPUT],
  4045. stream_.deviceFormat[INPUT] );
  4046. if ( callbackPulled ) {
  4047. if ( stream_.doConvertBuffer[INPUT] ) {
  4048. // Convert callback buffer to user format
  4049. convertBuffer( stream_.userBuffer[INPUT],
  4050. stream_.deviceBuffer,
  4051. stream_.convertInfo[INPUT] );
  4052. }
  4053. else {
  4054. // no further conversion, simple copy deviceBuffer to userBuffer
  4055. memcpy( stream_.userBuffer[INPUT],
  4056. stream_.deviceBuffer,
  4057. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4058. }
  4059. }
  4060. }
  4061. else {
  4062. // if there is no capture stream, set callbackPulled flag
  4063. callbackPulled = true;
  4064. }
  4065. // Execute Callback
  4066. // ================
  4067. // 1. Execute user callback method
  4068. // 2. Handle return value from callback
  4069. // if callback has not requested the stream to stop
  4070. if ( callbackPulled && !callbackStopped ) {
  4071. // Execute user callback method
  4072. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4073. stream_.userBuffer[INPUT],
  4074. stream_.bufferSize,
  4075. getStreamTime(),
  4076. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4077. stream_.callbackInfo.userData );
  4078. // Handle return value from callback
  4079. if ( callbackResult == 1 ) {
  4080. // instantiate a thread to stop this thread
  4081. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4082. if ( !threadHandle ) {
  4083. errorType = RtAudioError::THREAD_ERROR;
  4084. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4085. goto Exit;
  4086. }
  4087. else if ( !CloseHandle( threadHandle ) ) {
  4088. errorType = RtAudioError::THREAD_ERROR;
  4089. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4090. goto Exit;
  4091. }
  4092. callbackStopped = true;
  4093. }
  4094. else if ( callbackResult == 2 ) {
  4095. // instantiate a thread to stop this thread
  4096. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4097. if ( !threadHandle ) {
  4098. errorType = RtAudioError::THREAD_ERROR;
  4099. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4100. goto Exit;
  4101. }
  4102. else if ( !CloseHandle( threadHandle ) ) {
  4103. errorType = RtAudioError::THREAD_ERROR;
  4104. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4105. goto Exit;
  4106. }
  4107. callbackStopped = true;
  4108. }
  4109. }
  4110. }
  4111. // Callback Output
  4112. // ===============
  4113. // 1. Convert callback buffer to stream format
  4114. // 2. Push callback buffer into outputBuffer
  4115. if ( renderAudioClient && callbackPulled ) {
  4116. if ( stream_.doConvertBuffer[OUTPUT] ) {
  4117. // Convert callback buffer to stream format
  4118. convertBuffer( stream_.deviceBuffer,
  4119. stream_.userBuffer[OUTPUT],
  4120. stream_.convertInfo[OUTPUT] );
  4121. }
  4122. // Push callback buffer into outputBuffer
  4123. callbackPushed = renderBuffer.pushBuffer( stream_.deviceBuffer,
  4124. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT],
  4125. stream_.deviceFormat[OUTPUT] );
  4126. }
  4127. else {
  4128. // if there is no render stream, set callbackPushed flag
  4129. callbackPushed = true;
  4130. }
  4131. // Stream Capture
  4132. // ==============
  4133. // 1. Get capture buffer from stream
  4134. // 2. Push capture buffer into inputBuffer
  4135. // 3. If 2. was successful: Release capture buffer
  4136. if ( captureAudioClient ) {
  4137. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4138. if ( !callbackPulled ) {
  4139. WaitForSingleObject( captureEvent, INFINITE );
  4140. }
  4141. // Get capture buffer from stream
  4142. hr = captureClient->GetBuffer( &streamBuffer,
  4143. &bufferFrameCount,
  4144. &captureFlags, NULL, NULL );
  4145. if ( FAILED( hr ) ) {
  4146. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4147. goto Exit;
  4148. }
  4149. if ( bufferFrameCount != 0 ) {
  4150. // Push capture buffer into inputBuffer
  4151. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4152. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4153. stream_.deviceFormat[INPUT] ) )
  4154. {
  4155. // Release capture buffer
  4156. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4157. if ( FAILED( hr ) ) {
  4158. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4159. goto Exit;
  4160. }
  4161. }
  4162. else
  4163. {
  4164. // Inform WASAPI that capture was unsuccessful
  4165. hr = captureClient->ReleaseBuffer( 0 );
  4166. if ( FAILED( hr ) ) {
  4167. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4168. goto Exit;
  4169. }
  4170. }
  4171. }
  4172. else
  4173. {
  4174. // Inform WASAPI that capture was unsuccessful
  4175. hr = captureClient->ReleaseBuffer( 0 );
  4176. if ( FAILED( hr ) ) {
  4177. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4178. goto Exit;
  4179. }
  4180. }
  4181. }
  4182. // Stream Render
  4183. // =============
  4184. // 1. Get render buffer from stream
  4185. // 2. Pull next buffer from outputBuffer
  4186. // 3. If 2. was successful: Fill render buffer with next buffer
  4187. // Release render buffer
  4188. if ( renderAudioClient ) {
  4189. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4190. if ( callbackPulled && !callbackPushed ) {
  4191. WaitForSingleObject( renderEvent, INFINITE );
  4192. }
  4193. // Get render buffer from stream
  4194. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4195. if ( FAILED( hr ) ) {
  4196. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4197. goto Exit;
  4198. }
  4199. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4200. if ( FAILED( hr ) ) {
  4201. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4202. goto Exit;
  4203. }
  4204. bufferFrameCount -= numFramesPadding;
  4205. if ( bufferFrameCount != 0 ) {
  4206. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4207. if ( FAILED( hr ) ) {
  4208. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4209. goto Exit;
  4210. }
  4211. // Pull next buffer from outputBuffer
  4212. // Fill render buffer with next buffer
  4213. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4214. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4215. stream_.deviceFormat[OUTPUT] ) )
  4216. {
  4217. // Release render buffer
  4218. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4219. if ( FAILED( hr ) ) {
  4220. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4221. goto Exit;
  4222. }
  4223. }
  4224. else
  4225. {
  4226. // Inform WASAPI that render was unsuccessful
  4227. hr = renderClient->ReleaseBuffer( 0, 0 );
  4228. if ( FAILED( hr ) ) {
  4229. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4230. goto Exit;
  4231. }
  4232. }
  4233. }
  4234. else
  4235. {
  4236. // Inform WASAPI that render was unsuccessful
  4237. hr = renderClient->ReleaseBuffer( 0, 0 );
  4238. if ( FAILED( hr ) ) {
  4239. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4240. goto Exit;
  4241. }
  4242. }
  4243. }
  4244. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4245. if ( callbackPushed ) {
  4246. callbackPulled = false;
  4247. // tick stream time
  4248. RtApi::tickStreamTime();
  4249. }
  4250. }
  4251. Exit:
  4252. // clean up
  4253. CoTaskMemFree( captureFormat );
  4254. CoTaskMemFree( renderFormat );
  4255. CoUninitialize();
  4256. // update stream state
  4257. stream_.state = STREAM_STOPPED;
  4258. if ( errorText_.empty() )
  4259. return;
  4260. else
  4261. error( errorType );
  4262. }
  4263. //******************** End of __WINDOWS_WASAPI__ *********************//
  4264. #endif
  4265. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4266. // Modified by Robin Davies, October 2005
  4267. // - Improvements to DirectX pointer chasing.
  4268. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4269. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4270. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4271. // Changed device query structure for RtAudio 4.0.7, January 2010
  4272. #include <mmsystem.h>
  4273. #include <mmreg.h>
  4274. #include <dsound.h>
  4275. #include <assert.h>
  4276. #include <algorithm>
  4277. #if defined(__MINGW32__)
  4278. // missing from latest mingw winapi
  4279. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4280. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4281. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4282. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4283. #endif
  4284. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4285. #ifdef _MSC_VER // if Microsoft Visual C++
  4286. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4287. #endif
  4288. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4289. {
  4290. if ( pointer > bufferSize ) pointer -= bufferSize;
  4291. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4292. if ( pointer < earlierPointer ) pointer += bufferSize;
  4293. return pointer >= earlierPointer && pointer < laterPointer;
  4294. }
  4295. // A structure to hold various information related to the DirectSound
  4296. // API implementation.
  4297. struct DsHandle {
  4298. unsigned int drainCounter; // Tracks callback counts when draining
  4299. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4300. void *id[2];
  4301. void *buffer[2];
  4302. bool xrun[2];
  4303. UINT bufferPointer[2];
  4304. DWORD dsBufferSize[2];
  4305. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4306. HANDLE condition;
  4307. DsHandle()
  4308. :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }
  4309. };
  4310. // Declarations for utility functions, callbacks, and structures
  4311. // specific to the DirectSound implementation.
  4312. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4313. LPCTSTR description,
  4314. LPCTSTR module,
  4315. LPVOID lpContext );
  4316. static const char* getErrorString( int code );
  4317. static unsigned __stdcall callbackHandler( void *ptr );
  4318. struct DsDevice {
  4319. LPGUID id[2];
  4320. bool validId[2];
  4321. bool found;
  4322. std::string name;
  4323. DsDevice()
  4324. : found(false) { validId[0] = false; validId[1] = false; }
  4325. };
  4326. struct DsProbeData {
  4327. bool isInput;
  4328. std::vector<struct DsDevice>* dsDevices;
  4329. };
  4330. RtApiDs :: RtApiDs()
  4331. {
  4332. // Dsound will run both-threaded. If CoInitialize fails, then just
  4333. // accept whatever the mainline chose for a threading model.
  4334. coInitialized_ = false;
  4335. HRESULT hr = CoInitialize( NULL );
  4336. if ( !FAILED( hr ) ) coInitialized_ = true;
  4337. }
  4338. RtApiDs :: ~RtApiDs()
  4339. {
  4340. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4341. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4342. }
  4343. // The DirectSound default output is always the first device.
  4344. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4345. {
  4346. return 0;
  4347. }
  4348. // The DirectSound default input is always the first input device,
  4349. // which is the first capture device enumerated.
  4350. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4351. {
  4352. return 0;
  4353. }
  4354. unsigned int RtApiDs :: getDeviceCount( void )
  4355. {
  4356. // Set query flag for previously found devices to false, so that we
  4357. // can check for any devices that have disappeared.
  4358. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4359. dsDevices[i].found = false;
  4360. // Query DirectSound devices.
  4361. struct DsProbeData probeInfo;
  4362. probeInfo.isInput = false;
  4363. probeInfo.dsDevices = &dsDevices;
  4364. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4365. if ( FAILED( result ) ) {
  4366. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4367. errorText_ = errorStream_.str();
  4368. error( RtAudioError::WARNING );
  4369. }
  4370. // Query DirectSoundCapture devices.
  4371. probeInfo.isInput = true;
  4372. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4373. if ( FAILED( result ) ) {
  4374. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4375. errorText_ = errorStream_.str();
  4376. error( RtAudioError::WARNING );
  4377. }
  4378. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4379. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4380. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4381. else i++;
  4382. }
  4383. return static_cast<unsigned int>(dsDevices.size());
  4384. }
  4385. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4386. {
  4387. RtAudio::DeviceInfo info;
  4388. info.probed = false;
  4389. if ( dsDevices.size() == 0 ) {
  4390. // Force a query of all devices
  4391. getDeviceCount();
  4392. if ( dsDevices.size() == 0 ) {
  4393. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4394. error( RtAudioError::INVALID_USE );
  4395. return info;
  4396. }
  4397. }
  4398. if ( device >= dsDevices.size() ) {
  4399. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4400. error( RtAudioError::INVALID_USE );
  4401. return info;
  4402. }
  4403. HRESULT result;
  4404. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4405. LPDIRECTSOUND output;
  4406. DSCAPS outCaps;
  4407. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4408. if ( FAILED( result ) ) {
  4409. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4410. errorText_ = errorStream_.str();
  4411. error( RtAudioError::WARNING );
  4412. goto probeInput;
  4413. }
  4414. outCaps.dwSize = sizeof( outCaps );
  4415. result = output->GetCaps( &outCaps );
  4416. if ( FAILED( result ) ) {
  4417. output->Release();
  4418. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4419. errorText_ = errorStream_.str();
  4420. error( RtAudioError::WARNING );
  4421. goto probeInput;
  4422. }
  4423. // Get output channel information.
  4424. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4425. // Get sample rate information.
  4426. info.sampleRates.clear();
  4427. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4428. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4429. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4430. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4431. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4432. info.preferredSampleRate = SAMPLE_RATES[k];
  4433. }
  4434. }
  4435. // Get format information.
  4436. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4437. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4438. output->Release();
  4439. if ( getDefaultOutputDevice() == device )
  4440. info.isDefaultOutput = true;
  4441. if ( dsDevices[ device ].validId[1] == false ) {
  4442. info.name = dsDevices[ device ].name;
  4443. info.probed = true;
  4444. return info;
  4445. }
  4446. probeInput:
  4447. LPDIRECTSOUNDCAPTURE input;
  4448. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4449. if ( FAILED( result ) ) {
  4450. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4451. errorText_ = errorStream_.str();
  4452. error( RtAudioError::WARNING );
  4453. return info;
  4454. }
  4455. DSCCAPS inCaps;
  4456. inCaps.dwSize = sizeof( inCaps );
  4457. result = input->GetCaps( &inCaps );
  4458. if ( FAILED( result ) ) {
  4459. input->Release();
  4460. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4461. errorText_ = errorStream_.str();
  4462. error( RtAudioError::WARNING );
  4463. return info;
  4464. }
  4465. // Get input channel information.
  4466. info.inputChannels = inCaps.dwChannels;
  4467. // Get sample rate and format information.
  4468. std::vector<unsigned int> rates;
  4469. if ( inCaps.dwChannels >= 2 ) {
  4470. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4471. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4472. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4473. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4474. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4475. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4476. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4477. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4478. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4479. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4480. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4481. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4482. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4483. }
  4484. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4485. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4486. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4487. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4488. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4489. }
  4490. }
  4491. else if ( inCaps.dwChannels == 1 ) {
  4492. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4493. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4494. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4495. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4496. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4497. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4498. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4499. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4500. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4501. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4502. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4503. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4504. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4505. }
  4506. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4507. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4508. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4509. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4510. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4511. }
  4512. }
  4513. else info.inputChannels = 0; // technically, this would be an error
  4514. input->Release();
  4515. if ( info.inputChannels == 0 ) return info;
  4516. // Copy the supported rates to the info structure but avoid duplication.
  4517. bool found;
  4518. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4519. found = false;
  4520. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4521. if ( rates[i] == info.sampleRates[j] ) {
  4522. found = true;
  4523. break;
  4524. }
  4525. }
  4526. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4527. }
  4528. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4529. // If device opens for both playback and capture, we determine the channels.
  4530. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4531. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4532. if ( device == 0 ) info.isDefaultInput = true;
  4533. // Copy name and return.
  4534. info.name = dsDevices[ device ].name;
  4535. info.probed = true;
  4536. return info;
  4537. }
  4538. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4539. unsigned int firstChannel, unsigned int sampleRate,
  4540. RtAudioFormat format, unsigned int *bufferSize,
  4541. RtAudio::StreamOptions *options )
  4542. {
  4543. if ( channels + firstChannel > 2 ) {
  4544. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4545. return FAILURE;
  4546. }
  4547. size_t nDevices = dsDevices.size();
  4548. if ( nDevices == 0 ) {
  4549. // This should not happen because a check is made before this function is called.
  4550. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4551. return FAILURE;
  4552. }
  4553. if ( device >= nDevices ) {
  4554. // This should not happen because a check is made before this function is called.
  4555. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4556. return FAILURE;
  4557. }
  4558. if ( mode == OUTPUT ) {
  4559. if ( dsDevices[ device ].validId[0] == false ) {
  4560. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4561. errorText_ = errorStream_.str();
  4562. return FAILURE;
  4563. }
  4564. }
  4565. else { // mode == INPUT
  4566. if ( dsDevices[ device ].validId[1] == false ) {
  4567. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4568. errorText_ = errorStream_.str();
  4569. return FAILURE;
  4570. }
  4571. }
  4572. // According to a note in PortAudio, using GetDesktopWindow()
  4573. // instead of GetForegroundWindow() is supposed to avoid problems
  4574. // that occur when the application's window is not the foreground
  4575. // window. Also, if the application window closes before the
  4576. // DirectSound buffer, DirectSound can crash. In the past, I had
  4577. // problems when using GetDesktopWindow() but it seems fine now
  4578. // (January 2010). I'll leave it commented here.
  4579. // HWND hWnd = GetForegroundWindow();
  4580. HWND hWnd = GetDesktopWindow();
  4581. // Check the numberOfBuffers parameter and limit the lowest value to
  4582. // two. This is a judgement call and a value of two is probably too
  4583. // low for capture, but it should work for playback.
  4584. int nBuffers = 0;
  4585. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  4586. if ( options && options->numberOfBuffers > 0 ) nBuffers = options->numberOfBuffers;
  4587. if ( nBuffers < 2 ) nBuffers = 3;
  4588. // Check the lower range of the user-specified buffer size and set
  4589. // (arbitrarily) to a lower bound of 32.
  4590. if ( *bufferSize < 32 ) *bufferSize = 32;
  4591. // Create the wave format structure. The data format setting will
  4592. // be determined later.
  4593. WAVEFORMATEX waveFormat;
  4594. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  4595. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  4596. waveFormat.nChannels = channels + firstChannel;
  4597. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  4598. // Determine the device buffer size. By default, we'll use the value
  4599. // defined above (32K), but we will grow it to make allowances for
  4600. // very large software buffer sizes.
  4601. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  4602. DWORD dsPointerLeadTime = 0;
  4603. void *ohandle = 0, *bhandle = 0;
  4604. HRESULT result;
  4605. if ( mode == OUTPUT ) {
  4606. LPDIRECTSOUND output;
  4607. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4608. if ( FAILED( result ) ) {
  4609. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4610. errorText_ = errorStream_.str();
  4611. return FAILURE;
  4612. }
  4613. DSCAPS outCaps;
  4614. outCaps.dwSize = sizeof( outCaps );
  4615. result = output->GetCaps( &outCaps );
  4616. if ( FAILED( result ) ) {
  4617. output->Release();
  4618. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  4619. errorText_ = errorStream_.str();
  4620. return FAILURE;
  4621. }
  4622. // Check channel information.
  4623. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  4624. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  4625. errorText_ = errorStream_.str();
  4626. return FAILURE;
  4627. }
  4628. // Check format information. Use 16-bit format unless not
  4629. // supported or user requests 8-bit.
  4630. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  4631. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  4632. waveFormat.wBitsPerSample = 16;
  4633. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4634. }
  4635. else {
  4636. waveFormat.wBitsPerSample = 8;
  4637. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4638. }
  4639. stream_.userFormat = format;
  4640. // Update wave format structure and buffer information.
  4641. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4642. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4643. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4644. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4645. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4646. dsBufferSize *= 2;
  4647. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  4648. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  4649. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  4650. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  4651. if ( FAILED( result ) ) {
  4652. output->Release();
  4653. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  4654. errorText_ = errorStream_.str();
  4655. return FAILURE;
  4656. }
  4657. // Even though we will write to the secondary buffer, we need to
  4658. // access the primary buffer to set the correct output format
  4659. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  4660. // buffer description.
  4661. DSBUFFERDESC bufferDescription;
  4662. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4663. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4664. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  4665. // Obtain the primary buffer
  4666. LPDIRECTSOUNDBUFFER buffer;
  4667. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4668. if ( FAILED( result ) ) {
  4669. output->Release();
  4670. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  4671. errorText_ = errorStream_.str();
  4672. return FAILURE;
  4673. }
  4674. // Set the primary DS buffer sound format.
  4675. result = buffer->SetFormat( &waveFormat );
  4676. if ( FAILED( result ) ) {
  4677. output->Release();
  4678. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  4679. errorText_ = errorStream_.str();
  4680. return FAILURE;
  4681. }
  4682. // Setup the secondary DS buffer description.
  4683. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4684. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4685. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4686. DSBCAPS_GLOBALFOCUS |
  4687. DSBCAPS_GETCURRENTPOSITION2 |
  4688. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  4689. bufferDescription.dwBufferBytes = dsBufferSize;
  4690. bufferDescription.lpwfxFormat = &waveFormat;
  4691. // Try to create the secondary DS buffer. If that doesn't work,
  4692. // try to use software mixing. Otherwise, there's a problem.
  4693. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4694. if ( FAILED( result ) ) {
  4695. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4696. DSBCAPS_GLOBALFOCUS |
  4697. DSBCAPS_GETCURRENTPOSITION2 |
  4698. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  4699. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4700. if ( FAILED( result ) ) {
  4701. output->Release();
  4702. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  4703. errorText_ = errorStream_.str();
  4704. return FAILURE;
  4705. }
  4706. }
  4707. // Get the buffer size ... might be different from what we specified.
  4708. DSBCAPS dsbcaps;
  4709. dsbcaps.dwSize = sizeof( DSBCAPS );
  4710. result = buffer->GetCaps( &dsbcaps );
  4711. if ( FAILED( result ) ) {
  4712. output->Release();
  4713. buffer->Release();
  4714. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4715. errorText_ = errorStream_.str();
  4716. return FAILURE;
  4717. }
  4718. dsBufferSize = dsbcaps.dwBufferBytes;
  4719. // Lock the DS buffer
  4720. LPVOID audioPtr;
  4721. DWORD dataLen;
  4722. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4723. if ( FAILED( result ) ) {
  4724. output->Release();
  4725. buffer->Release();
  4726. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  4727. errorText_ = errorStream_.str();
  4728. return FAILURE;
  4729. }
  4730. // Zero the DS buffer
  4731. ZeroMemory( audioPtr, dataLen );
  4732. // Unlock the DS buffer
  4733. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4734. if ( FAILED( result ) ) {
  4735. output->Release();
  4736. buffer->Release();
  4737. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  4738. errorText_ = errorStream_.str();
  4739. return FAILURE;
  4740. }
  4741. ohandle = (void *) output;
  4742. bhandle = (void *) buffer;
  4743. }
  4744. if ( mode == INPUT ) {
  4745. LPDIRECTSOUNDCAPTURE input;
  4746. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4747. if ( FAILED( result ) ) {
  4748. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4749. errorText_ = errorStream_.str();
  4750. return FAILURE;
  4751. }
  4752. DSCCAPS inCaps;
  4753. inCaps.dwSize = sizeof( inCaps );
  4754. result = input->GetCaps( &inCaps );
  4755. if ( FAILED( result ) ) {
  4756. input->Release();
  4757. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  4758. errorText_ = errorStream_.str();
  4759. return FAILURE;
  4760. }
  4761. // Check channel information.
  4762. if ( inCaps.dwChannels < channels + firstChannel ) {
  4763. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  4764. return FAILURE;
  4765. }
  4766. // Check format information. Use 16-bit format unless user
  4767. // requests 8-bit.
  4768. DWORD deviceFormats;
  4769. if ( channels + firstChannel == 2 ) {
  4770. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  4771. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4772. waveFormat.wBitsPerSample = 8;
  4773. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4774. }
  4775. else { // assume 16-bit is supported
  4776. waveFormat.wBitsPerSample = 16;
  4777. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4778. }
  4779. }
  4780. else { // channel == 1
  4781. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  4782. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4783. waveFormat.wBitsPerSample = 8;
  4784. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4785. }
  4786. else { // assume 16-bit is supported
  4787. waveFormat.wBitsPerSample = 16;
  4788. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4789. }
  4790. }
  4791. stream_.userFormat = format;
  4792. // Update wave format structure and buffer information.
  4793. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4794. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4795. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4796. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4797. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4798. dsBufferSize *= 2;
  4799. // Setup the secondary DS buffer description.
  4800. DSCBUFFERDESC bufferDescription;
  4801. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  4802. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  4803. bufferDescription.dwFlags = 0;
  4804. bufferDescription.dwReserved = 0;
  4805. bufferDescription.dwBufferBytes = dsBufferSize;
  4806. bufferDescription.lpwfxFormat = &waveFormat;
  4807. // Create the capture buffer.
  4808. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  4809. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  4810. if ( FAILED( result ) ) {
  4811. input->Release();
  4812. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  4813. errorText_ = errorStream_.str();
  4814. return FAILURE;
  4815. }
  4816. // Get the buffer size ... might be different from what we specified.
  4817. DSCBCAPS dscbcaps;
  4818. dscbcaps.dwSize = sizeof( DSCBCAPS );
  4819. result = buffer->GetCaps( &dscbcaps );
  4820. if ( FAILED( result ) ) {
  4821. input->Release();
  4822. buffer->Release();
  4823. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4824. errorText_ = errorStream_.str();
  4825. return FAILURE;
  4826. }
  4827. dsBufferSize = dscbcaps.dwBufferBytes;
  4828. // NOTE: We could have a problem here if this is a duplex stream
  4829. // and the play and capture hardware buffer sizes are different
  4830. // (I'm actually not sure if that is a problem or not).
  4831. // Currently, we are not verifying that.
  4832. // Lock the capture buffer
  4833. LPVOID audioPtr;
  4834. DWORD dataLen;
  4835. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4836. if ( FAILED( result ) ) {
  4837. input->Release();
  4838. buffer->Release();
  4839. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  4840. errorText_ = errorStream_.str();
  4841. return FAILURE;
  4842. }
  4843. // Zero the buffer
  4844. ZeroMemory( audioPtr, dataLen );
  4845. // Unlock the buffer
  4846. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4847. if ( FAILED( result ) ) {
  4848. input->Release();
  4849. buffer->Release();
  4850. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  4851. errorText_ = errorStream_.str();
  4852. return FAILURE;
  4853. }
  4854. ohandle = (void *) input;
  4855. bhandle = (void *) buffer;
  4856. }
  4857. // Set various stream parameters
  4858. DsHandle *handle = 0;
  4859. stream_.nDeviceChannels[mode] = channels + firstChannel;
  4860. stream_.nUserChannels[mode] = channels;
  4861. stream_.bufferSize = *bufferSize;
  4862. stream_.channelOffset[mode] = firstChannel;
  4863. stream_.deviceInterleaved[mode] = true;
  4864. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  4865. else stream_.userInterleaved = true;
  4866. // Set flag for buffer conversion
  4867. stream_.doConvertBuffer[mode] = false;
  4868. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  4869. stream_.doConvertBuffer[mode] = true;
  4870. if (stream_.userFormat != stream_.deviceFormat[mode])
  4871. stream_.doConvertBuffer[mode] = true;
  4872. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4873. stream_.nUserChannels[mode] > 1 )
  4874. stream_.doConvertBuffer[mode] = true;
  4875. // Allocate necessary internal buffers
  4876. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  4877. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  4878. if ( stream_.userBuffer[mode] == NULL ) {
  4879. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  4880. goto error;
  4881. }
  4882. if ( stream_.doConvertBuffer[mode] ) {
  4883. bool makeBuffer = true;
  4884. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  4885. if ( mode == INPUT ) {
  4886. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  4887. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  4888. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  4889. }
  4890. }
  4891. if ( makeBuffer ) {
  4892. bufferBytes *= *bufferSize;
  4893. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  4894. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  4895. if ( stream_.deviceBuffer == NULL ) {
  4896. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  4897. goto error;
  4898. }
  4899. }
  4900. }
  4901. // Allocate our DsHandle structures for the stream.
  4902. if ( stream_.apiHandle == 0 ) {
  4903. try {
  4904. handle = new DsHandle;
  4905. }
  4906. catch ( std::bad_alloc& ) {
  4907. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  4908. goto error;
  4909. }
  4910. // Create a manual-reset event.
  4911. handle->condition = CreateEvent( NULL, // no security
  4912. TRUE, // manual-reset
  4913. FALSE, // non-signaled initially
  4914. NULL ); // unnamed
  4915. stream_.apiHandle = (void *) handle;
  4916. }
  4917. else
  4918. handle = (DsHandle *) stream_.apiHandle;
  4919. handle->id[mode] = ohandle;
  4920. handle->buffer[mode] = bhandle;
  4921. handle->dsBufferSize[mode] = dsBufferSize;
  4922. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  4923. stream_.device[mode] = device;
  4924. stream_.state = STREAM_STOPPED;
  4925. if ( stream_.mode == OUTPUT && mode == INPUT )
  4926. // We had already set up an output stream.
  4927. stream_.mode = DUPLEX;
  4928. else
  4929. stream_.mode = mode;
  4930. stream_.nBuffers = nBuffers;
  4931. stream_.sampleRate = sampleRate;
  4932. // Setup the buffer conversion information structure.
  4933. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  4934. // Setup the callback thread.
  4935. if ( stream_.callbackInfo.isRunning == false ) {
  4936. unsigned threadId;
  4937. stream_.callbackInfo.isRunning = true;
  4938. stream_.callbackInfo.object = (void *) this;
  4939. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  4940. &stream_.callbackInfo, 0, &threadId );
  4941. if ( stream_.callbackInfo.thread == 0 ) {
  4942. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  4943. goto error;
  4944. }
  4945. // Boost DS thread priority
  4946. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  4947. }
  4948. return SUCCESS;
  4949. error:
  4950. if ( handle ) {
  4951. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  4952. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  4953. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  4954. if ( buffer ) buffer->Release();
  4955. object->Release();
  4956. }
  4957. if ( handle->buffer[1] ) {
  4958. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  4959. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  4960. if ( buffer ) buffer->Release();
  4961. object->Release();
  4962. }
  4963. CloseHandle( handle->condition );
  4964. delete handle;
  4965. stream_.apiHandle = 0;
  4966. }
  4967. for ( int i=0; i<2; i++ ) {
  4968. if ( stream_.userBuffer[i] ) {
  4969. free( stream_.userBuffer[i] );
  4970. stream_.userBuffer[i] = 0;
  4971. }
  4972. }
  4973. if ( stream_.deviceBuffer ) {
  4974. free( stream_.deviceBuffer );
  4975. stream_.deviceBuffer = 0;
  4976. }
  4977. stream_.state = STREAM_CLOSED;
  4978. return FAILURE;
  4979. }
  4980. void RtApiDs :: closeStream()
  4981. {
  4982. if ( stream_.state == STREAM_CLOSED ) {
  4983. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  4984. error( RtAudioError::WARNING );
  4985. return;
  4986. }
  4987. // Stop the callback thread.
  4988. stream_.callbackInfo.isRunning = false;
  4989. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  4990. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  4991. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  4992. if ( handle ) {
  4993. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  4994. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  4995. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  4996. if ( buffer ) {
  4997. buffer->Stop();
  4998. buffer->Release();
  4999. }
  5000. object->Release();
  5001. }
  5002. if ( handle->buffer[1] ) {
  5003. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5004. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5005. if ( buffer ) {
  5006. buffer->Stop();
  5007. buffer->Release();
  5008. }
  5009. object->Release();
  5010. }
  5011. CloseHandle( handle->condition );
  5012. delete handle;
  5013. stream_.apiHandle = 0;
  5014. }
  5015. for ( int i=0; i<2; i++ ) {
  5016. if ( stream_.userBuffer[i] ) {
  5017. free( stream_.userBuffer[i] );
  5018. stream_.userBuffer[i] = 0;
  5019. }
  5020. }
  5021. if ( stream_.deviceBuffer ) {
  5022. free( stream_.deviceBuffer );
  5023. stream_.deviceBuffer = 0;
  5024. }
  5025. stream_.mode = UNINITIALIZED;
  5026. stream_.state = STREAM_CLOSED;
  5027. }
  5028. void RtApiDs :: startStream()
  5029. {
  5030. verifyStream();
  5031. if ( stream_.state == STREAM_RUNNING ) {
  5032. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5033. error( RtAudioError::WARNING );
  5034. return;
  5035. }
  5036. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5037. // Increase scheduler frequency on lesser windows (a side-effect of
  5038. // increasing timer accuracy). On greater windows (Win2K or later),
  5039. // this is already in effect.
  5040. timeBeginPeriod( 1 );
  5041. buffersRolling = false;
  5042. duplexPrerollBytes = 0;
  5043. if ( stream_.mode == DUPLEX ) {
  5044. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5045. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5046. }
  5047. HRESULT result = 0;
  5048. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5049. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5050. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5051. if ( FAILED( result ) ) {
  5052. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5053. errorText_ = errorStream_.str();
  5054. goto unlock;
  5055. }
  5056. }
  5057. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5058. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5059. result = buffer->Start( DSCBSTART_LOOPING );
  5060. if ( FAILED( result ) ) {
  5061. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5062. errorText_ = errorStream_.str();
  5063. goto unlock;
  5064. }
  5065. }
  5066. handle->drainCounter = 0;
  5067. handle->internalDrain = false;
  5068. ResetEvent( handle->condition );
  5069. stream_.state = STREAM_RUNNING;
  5070. unlock:
  5071. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5072. }
  5073. void RtApiDs :: stopStream()
  5074. {
  5075. verifyStream();
  5076. if ( stream_.state == STREAM_STOPPED ) {
  5077. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5078. error( RtAudioError::WARNING );
  5079. return;
  5080. }
  5081. HRESULT result = 0;
  5082. LPVOID audioPtr;
  5083. DWORD dataLen;
  5084. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5085. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5086. if ( handle->drainCounter == 0 ) {
  5087. handle->drainCounter = 2;
  5088. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5089. }
  5090. stream_.state = STREAM_STOPPED;
  5091. MUTEX_LOCK( &stream_.mutex );
  5092. // Stop the buffer and clear memory
  5093. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5094. result = buffer->Stop();
  5095. if ( FAILED( result ) ) {
  5096. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5097. errorText_ = errorStream_.str();
  5098. goto unlock;
  5099. }
  5100. // Lock the buffer and clear it so that if we start to play again,
  5101. // we won't have old data playing.
  5102. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5103. if ( FAILED( result ) ) {
  5104. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5105. errorText_ = errorStream_.str();
  5106. goto unlock;
  5107. }
  5108. // Zero the DS buffer
  5109. ZeroMemory( audioPtr, dataLen );
  5110. // Unlock the DS buffer
  5111. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5112. if ( FAILED( result ) ) {
  5113. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5114. errorText_ = errorStream_.str();
  5115. goto unlock;
  5116. }
  5117. // If we start playing again, we must begin at beginning of buffer.
  5118. handle->bufferPointer[0] = 0;
  5119. }
  5120. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5121. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5122. audioPtr = NULL;
  5123. dataLen = 0;
  5124. stream_.state = STREAM_STOPPED;
  5125. if ( stream_.mode != DUPLEX )
  5126. MUTEX_LOCK( &stream_.mutex );
  5127. result = buffer->Stop();
  5128. if ( FAILED( result ) ) {
  5129. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5130. errorText_ = errorStream_.str();
  5131. goto unlock;
  5132. }
  5133. // Lock the buffer and clear it so that if we start to play again,
  5134. // we won't have old data playing.
  5135. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5136. if ( FAILED( result ) ) {
  5137. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5138. errorText_ = errorStream_.str();
  5139. goto unlock;
  5140. }
  5141. // Zero the DS buffer
  5142. ZeroMemory( audioPtr, dataLen );
  5143. // Unlock the DS buffer
  5144. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5145. if ( FAILED( result ) ) {
  5146. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5147. errorText_ = errorStream_.str();
  5148. goto unlock;
  5149. }
  5150. // If we start recording again, we must begin at beginning of buffer.
  5151. handle->bufferPointer[1] = 0;
  5152. }
  5153. unlock:
  5154. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5155. MUTEX_UNLOCK( &stream_.mutex );
  5156. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5157. }
  5158. void RtApiDs :: abortStream()
  5159. {
  5160. verifyStream();
  5161. if ( stream_.state == STREAM_STOPPED ) {
  5162. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5163. error( RtAudioError::WARNING );
  5164. return;
  5165. }
  5166. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5167. handle->drainCounter = 2;
  5168. stopStream();
  5169. }
  5170. void RtApiDs :: callbackEvent()
  5171. {
  5172. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5173. Sleep( 50 ); // sleep 50 milliseconds
  5174. return;
  5175. }
  5176. if ( stream_.state == STREAM_CLOSED ) {
  5177. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5178. error( RtAudioError::WARNING );
  5179. return;
  5180. }
  5181. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5182. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5183. // Check if we were draining the stream and signal is finished.
  5184. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5185. stream_.state = STREAM_STOPPING;
  5186. if ( handle->internalDrain == false )
  5187. SetEvent( handle->condition );
  5188. else
  5189. stopStream();
  5190. return;
  5191. }
  5192. // Invoke user callback to get fresh output data UNLESS we are
  5193. // draining stream.
  5194. if ( handle->drainCounter == 0 ) {
  5195. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5196. double streamTime = getStreamTime();
  5197. RtAudioStreamStatus status = 0;
  5198. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5199. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5200. handle->xrun[0] = false;
  5201. }
  5202. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5203. status |= RTAUDIO_INPUT_OVERFLOW;
  5204. handle->xrun[1] = false;
  5205. }
  5206. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5207. stream_.bufferSize, streamTime, status, info->userData );
  5208. if ( cbReturnValue == 2 ) {
  5209. stream_.state = STREAM_STOPPING;
  5210. handle->drainCounter = 2;
  5211. abortStream();
  5212. return;
  5213. }
  5214. else if ( cbReturnValue == 1 ) {
  5215. handle->drainCounter = 1;
  5216. handle->internalDrain = true;
  5217. }
  5218. }
  5219. HRESULT result;
  5220. DWORD currentWritePointer, safeWritePointer;
  5221. DWORD currentReadPointer, safeReadPointer;
  5222. UINT nextWritePointer;
  5223. LPVOID buffer1 = NULL;
  5224. LPVOID buffer2 = NULL;
  5225. DWORD bufferSize1 = 0;
  5226. DWORD bufferSize2 = 0;
  5227. char *buffer;
  5228. long bufferBytes;
  5229. MUTEX_LOCK( &stream_.mutex );
  5230. if ( stream_.state == STREAM_STOPPED ) {
  5231. MUTEX_UNLOCK( &stream_.mutex );
  5232. return;
  5233. }
  5234. if ( buffersRolling == false ) {
  5235. if ( stream_.mode == DUPLEX ) {
  5236. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5237. // It takes a while for the devices to get rolling. As a result,
  5238. // there's no guarantee that the capture and write device pointers
  5239. // will move in lockstep. Wait here for both devices to start
  5240. // rolling, and then set our buffer pointers accordingly.
  5241. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5242. // bytes later than the write buffer.
  5243. // Stub: a serious risk of having a pre-emptive scheduling round
  5244. // take place between the two GetCurrentPosition calls... but I'm
  5245. // really not sure how to solve the problem. Temporarily boost to
  5246. // Realtime priority, maybe; but I'm not sure what priority the
  5247. // DirectSound service threads run at. We *should* be roughly
  5248. // within a ms or so of correct.
  5249. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5250. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5251. DWORD startSafeWritePointer, startSafeReadPointer;
  5252. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5253. if ( FAILED( result ) ) {
  5254. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5255. errorText_ = errorStream_.str();
  5256. MUTEX_UNLOCK( &stream_.mutex );
  5257. error( RtAudioError::SYSTEM_ERROR );
  5258. return;
  5259. }
  5260. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5261. if ( FAILED( result ) ) {
  5262. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5263. errorText_ = errorStream_.str();
  5264. MUTEX_UNLOCK( &stream_.mutex );
  5265. error( RtAudioError::SYSTEM_ERROR );
  5266. return;
  5267. }
  5268. while ( true ) {
  5269. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5270. if ( FAILED( result ) ) {
  5271. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5272. errorText_ = errorStream_.str();
  5273. MUTEX_UNLOCK( &stream_.mutex );
  5274. error( RtAudioError::SYSTEM_ERROR );
  5275. return;
  5276. }
  5277. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5278. if ( FAILED( result ) ) {
  5279. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5280. errorText_ = errorStream_.str();
  5281. MUTEX_UNLOCK( &stream_.mutex );
  5282. error( RtAudioError::SYSTEM_ERROR );
  5283. return;
  5284. }
  5285. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5286. Sleep( 1 );
  5287. }
  5288. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5289. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5290. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5291. handle->bufferPointer[1] = safeReadPointer;
  5292. }
  5293. else if ( stream_.mode == OUTPUT ) {
  5294. // Set the proper nextWritePosition after initial startup.
  5295. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5296. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5297. if ( FAILED( result ) ) {
  5298. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5299. errorText_ = errorStream_.str();
  5300. MUTEX_UNLOCK( &stream_.mutex );
  5301. error( RtAudioError::SYSTEM_ERROR );
  5302. return;
  5303. }
  5304. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5305. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5306. }
  5307. buffersRolling = true;
  5308. }
  5309. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5310. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5311. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5312. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5313. bufferBytes *= formatBytes( stream_.userFormat );
  5314. memset( stream_.userBuffer[0], 0, bufferBytes );
  5315. }
  5316. // Setup parameters and do buffer conversion if necessary.
  5317. if ( stream_.doConvertBuffer[0] ) {
  5318. buffer = stream_.deviceBuffer;
  5319. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5320. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5321. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5322. }
  5323. else {
  5324. buffer = stream_.userBuffer[0];
  5325. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5326. bufferBytes *= formatBytes( stream_.userFormat );
  5327. }
  5328. // No byte swapping necessary in DirectSound implementation.
  5329. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5330. // unsigned. So, we need to convert our signed 8-bit data here to
  5331. // unsigned.
  5332. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5333. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5334. DWORD dsBufferSize = handle->dsBufferSize[0];
  5335. nextWritePointer = handle->bufferPointer[0];
  5336. DWORD endWrite, leadPointer;
  5337. while ( true ) {
  5338. // Find out where the read and "safe write" pointers are.
  5339. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5340. if ( FAILED( result ) ) {
  5341. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5342. errorText_ = errorStream_.str();
  5343. MUTEX_UNLOCK( &stream_.mutex );
  5344. error( RtAudioError::SYSTEM_ERROR );
  5345. return;
  5346. }
  5347. // We will copy our output buffer into the region between
  5348. // safeWritePointer and leadPointer. If leadPointer is not
  5349. // beyond the next endWrite position, wait until it is.
  5350. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5351. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5352. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5353. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5354. endWrite = nextWritePointer + bufferBytes;
  5355. // Check whether the entire write region is behind the play pointer.
  5356. if ( leadPointer >= endWrite ) break;
  5357. // If we are here, then we must wait until the leadPointer advances
  5358. // beyond the end of our next write region. We use the
  5359. // Sleep() function to suspend operation until that happens.
  5360. double millis = ( endWrite - leadPointer ) * 1000.0;
  5361. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5362. if ( millis < 1.0 ) millis = 1.0;
  5363. Sleep( (DWORD) millis );
  5364. }
  5365. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5366. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5367. // We've strayed into the forbidden zone ... resync the read pointer.
  5368. handle->xrun[0] = true;
  5369. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5370. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5371. handle->bufferPointer[0] = nextWritePointer;
  5372. endWrite = nextWritePointer + bufferBytes;
  5373. }
  5374. // Lock free space in the buffer
  5375. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5376. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5377. if ( FAILED( result ) ) {
  5378. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5379. errorText_ = errorStream_.str();
  5380. MUTEX_UNLOCK( &stream_.mutex );
  5381. error( RtAudioError::SYSTEM_ERROR );
  5382. return;
  5383. }
  5384. // Copy our buffer into the DS buffer
  5385. CopyMemory( buffer1, buffer, bufferSize1 );
  5386. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5387. // Update our buffer offset and unlock sound buffer
  5388. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5389. if ( FAILED( result ) ) {
  5390. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5391. errorText_ = errorStream_.str();
  5392. MUTEX_UNLOCK( &stream_.mutex );
  5393. error( RtAudioError::SYSTEM_ERROR );
  5394. return;
  5395. }
  5396. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5397. handle->bufferPointer[0] = nextWritePointer;
  5398. }
  5399. // Don't bother draining input
  5400. if ( handle->drainCounter ) {
  5401. handle->drainCounter++;
  5402. goto unlock;
  5403. }
  5404. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5405. // Setup parameters.
  5406. if ( stream_.doConvertBuffer[1] ) {
  5407. buffer = stream_.deviceBuffer;
  5408. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5409. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5410. }
  5411. else {
  5412. buffer = stream_.userBuffer[1];
  5413. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5414. bufferBytes *= formatBytes( stream_.userFormat );
  5415. }
  5416. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5417. long nextReadPointer = handle->bufferPointer[1];
  5418. DWORD dsBufferSize = handle->dsBufferSize[1];
  5419. // Find out where the write and "safe read" pointers are.
  5420. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5421. if ( FAILED( result ) ) {
  5422. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5423. errorText_ = errorStream_.str();
  5424. MUTEX_UNLOCK( &stream_.mutex );
  5425. error( RtAudioError::SYSTEM_ERROR );
  5426. return;
  5427. }
  5428. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5429. DWORD endRead = nextReadPointer + bufferBytes;
  5430. // Handling depends on whether we are INPUT or DUPLEX.
  5431. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5432. // then a wait here will drag the write pointers into the forbidden zone.
  5433. //
  5434. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5435. // it's in a safe position. This causes dropouts, but it seems to be the only
  5436. // practical way to sync up the read and write pointers reliably, given the
  5437. // the very complex relationship between phase and increment of the read and write
  5438. // pointers.
  5439. //
  5440. // In order to minimize audible dropouts in DUPLEX mode, we will
  5441. // provide a pre-roll period of 0.5 seconds in which we return
  5442. // zeros from the read buffer while the pointers sync up.
  5443. if ( stream_.mode == DUPLEX ) {
  5444. if ( safeReadPointer < endRead ) {
  5445. if ( duplexPrerollBytes <= 0 ) {
  5446. // Pre-roll time over. Be more agressive.
  5447. int adjustment = endRead-safeReadPointer;
  5448. handle->xrun[1] = true;
  5449. // Two cases:
  5450. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5451. // and perform fine adjustments later.
  5452. // - small adjustments: back off by twice as much.
  5453. if ( adjustment >= 2*bufferBytes )
  5454. nextReadPointer = safeReadPointer-2*bufferBytes;
  5455. else
  5456. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5457. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5458. }
  5459. else {
  5460. // In pre=roll time. Just do it.
  5461. nextReadPointer = safeReadPointer - bufferBytes;
  5462. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5463. }
  5464. endRead = nextReadPointer + bufferBytes;
  5465. }
  5466. }
  5467. else { // mode == INPUT
  5468. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5469. // See comments for playback.
  5470. double millis = (endRead - safeReadPointer) * 1000.0;
  5471. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5472. if ( millis < 1.0 ) millis = 1.0;
  5473. Sleep( (DWORD) millis );
  5474. // Wake up and find out where we are now.
  5475. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5476. if ( FAILED( result ) ) {
  5477. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5478. errorText_ = errorStream_.str();
  5479. MUTEX_UNLOCK( &stream_.mutex );
  5480. error( RtAudioError::SYSTEM_ERROR );
  5481. return;
  5482. }
  5483. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5484. }
  5485. }
  5486. // Lock free space in the buffer
  5487. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5488. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5489. if ( FAILED( result ) ) {
  5490. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5491. errorText_ = errorStream_.str();
  5492. MUTEX_UNLOCK( &stream_.mutex );
  5493. error( RtAudioError::SYSTEM_ERROR );
  5494. return;
  5495. }
  5496. if ( duplexPrerollBytes <= 0 ) {
  5497. // Copy our buffer into the DS buffer
  5498. CopyMemory( buffer, buffer1, bufferSize1 );
  5499. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5500. }
  5501. else {
  5502. memset( buffer, 0, bufferSize1 );
  5503. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5504. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5505. }
  5506. // Update our buffer offset and unlock sound buffer
  5507. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5508. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5509. if ( FAILED( result ) ) {
  5510. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5511. errorText_ = errorStream_.str();
  5512. MUTEX_UNLOCK( &stream_.mutex );
  5513. error( RtAudioError::SYSTEM_ERROR );
  5514. return;
  5515. }
  5516. handle->bufferPointer[1] = nextReadPointer;
  5517. // No byte swapping necessary in DirectSound implementation.
  5518. // If necessary, convert 8-bit data from unsigned to signed.
  5519. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5520. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5521. // Do buffer conversion if necessary.
  5522. if ( stream_.doConvertBuffer[1] )
  5523. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5524. }
  5525. unlock:
  5526. MUTEX_UNLOCK( &stream_.mutex );
  5527. RtApi::tickStreamTime();
  5528. }
  5529. // Definitions for utility functions and callbacks
  5530. // specific to the DirectSound implementation.
  5531. static unsigned __stdcall callbackHandler( void *ptr )
  5532. {
  5533. CallbackInfo *info = (CallbackInfo *) ptr;
  5534. RtApiDs *object = (RtApiDs *) info->object;
  5535. bool* isRunning = &info->isRunning;
  5536. while ( *isRunning == true ) {
  5537. object->callbackEvent();
  5538. }
  5539. _endthreadex( 0 );
  5540. return 0;
  5541. }
  5542. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5543. LPCTSTR description,
  5544. LPCTSTR /*module*/,
  5545. LPVOID lpContext )
  5546. {
  5547. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5548. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5549. HRESULT hr;
  5550. bool validDevice = false;
  5551. if ( probeInfo.isInput == true ) {
  5552. DSCCAPS caps;
  5553. LPDIRECTSOUNDCAPTURE object;
  5554. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5555. if ( hr != DS_OK ) return TRUE;
  5556. caps.dwSize = sizeof(caps);
  5557. hr = object->GetCaps( &caps );
  5558. if ( hr == DS_OK ) {
  5559. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5560. validDevice = true;
  5561. }
  5562. object->Release();
  5563. }
  5564. else {
  5565. DSCAPS caps;
  5566. LPDIRECTSOUND object;
  5567. hr = DirectSoundCreate( lpguid, &object, NULL );
  5568. if ( hr != DS_OK ) return TRUE;
  5569. caps.dwSize = sizeof(caps);
  5570. hr = object->GetCaps( &caps );
  5571. if ( hr == DS_OK ) {
  5572. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  5573. validDevice = true;
  5574. }
  5575. object->Release();
  5576. }
  5577. // If good device, then save its name and guid.
  5578. std::string name = convertCharPointerToStdString( description );
  5579. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  5580. if ( lpguid == NULL )
  5581. name = "Default Device";
  5582. if ( validDevice ) {
  5583. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  5584. if ( dsDevices[i].name == name ) {
  5585. dsDevices[i].found = true;
  5586. if ( probeInfo.isInput ) {
  5587. dsDevices[i].id[1] = lpguid;
  5588. dsDevices[i].validId[1] = true;
  5589. }
  5590. else {
  5591. dsDevices[i].id[0] = lpguid;
  5592. dsDevices[i].validId[0] = true;
  5593. }
  5594. return TRUE;
  5595. }
  5596. }
  5597. DsDevice device;
  5598. device.name = name;
  5599. device.found = true;
  5600. if ( probeInfo.isInput ) {
  5601. device.id[1] = lpguid;
  5602. device.validId[1] = true;
  5603. }
  5604. else {
  5605. device.id[0] = lpguid;
  5606. device.validId[0] = true;
  5607. }
  5608. dsDevices.push_back( device );
  5609. }
  5610. return TRUE;
  5611. }
  5612. static const char* getErrorString( int code )
  5613. {
  5614. switch ( code ) {
  5615. case DSERR_ALLOCATED:
  5616. return "Already allocated";
  5617. case DSERR_CONTROLUNAVAIL:
  5618. return "Control unavailable";
  5619. case DSERR_INVALIDPARAM:
  5620. return "Invalid parameter";
  5621. case DSERR_INVALIDCALL:
  5622. return "Invalid call";
  5623. case DSERR_GENERIC:
  5624. return "Generic error";
  5625. case DSERR_PRIOLEVELNEEDED:
  5626. return "Priority level needed";
  5627. case DSERR_OUTOFMEMORY:
  5628. return "Out of memory";
  5629. case DSERR_BADFORMAT:
  5630. return "The sample rate or the channel format is not supported";
  5631. case DSERR_UNSUPPORTED:
  5632. return "Not supported";
  5633. case DSERR_NODRIVER:
  5634. return "No driver";
  5635. case DSERR_ALREADYINITIALIZED:
  5636. return "Already initialized";
  5637. case DSERR_NOAGGREGATION:
  5638. return "No aggregation";
  5639. case DSERR_BUFFERLOST:
  5640. return "Buffer lost";
  5641. case DSERR_OTHERAPPHASPRIO:
  5642. return "Another application already has priority";
  5643. case DSERR_UNINITIALIZED:
  5644. return "Uninitialized";
  5645. default:
  5646. return "DirectSound unknown error";
  5647. }
  5648. }
  5649. //******************** End of __WINDOWS_DS__ *********************//
  5650. #endif
  5651. #if defined(__LINUX_ALSA__)
  5652. #include <alsa/asoundlib.h>
  5653. #include <unistd.h>
  5654. // A structure to hold various information related to the ALSA API
  5655. // implementation.
  5656. struct AlsaHandle {
  5657. snd_pcm_t *handles[2];
  5658. bool synchronized;
  5659. bool xrun[2];
  5660. pthread_cond_t runnable_cv;
  5661. bool runnable;
  5662. AlsaHandle()
  5663. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  5664. };
  5665. static void *alsaCallbackHandler( void * ptr );
  5666. RtApiAlsa :: RtApiAlsa()
  5667. {
  5668. // Nothing to do here.
  5669. }
  5670. RtApiAlsa :: ~RtApiAlsa()
  5671. {
  5672. if ( stream_.state != STREAM_CLOSED ) closeStream();
  5673. }
  5674. unsigned int RtApiAlsa :: getDeviceCount( void )
  5675. {
  5676. unsigned nDevices = 0;
  5677. int result, subdevice, card;
  5678. char name[64];
  5679. snd_ctl_t *handle;
  5680. // Count cards and devices
  5681. card = -1;
  5682. snd_card_next( &card );
  5683. while ( card >= 0 ) {
  5684. sprintf( name, "hw:%d", card );
  5685. result = snd_ctl_open( &handle, name, 0 );
  5686. if ( result < 0 ) {
  5687. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5688. errorText_ = errorStream_.str();
  5689. error( RtAudioError::WARNING );
  5690. goto nextcard;
  5691. }
  5692. subdevice = -1;
  5693. while( 1 ) {
  5694. result = snd_ctl_pcm_next_device( handle, &subdevice );
  5695. if ( result < 0 ) {
  5696. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5697. errorText_ = errorStream_.str();
  5698. error( RtAudioError::WARNING );
  5699. break;
  5700. }
  5701. if ( subdevice < 0 )
  5702. break;
  5703. nDevices++;
  5704. }
  5705. nextcard:
  5706. snd_ctl_close( handle );
  5707. snd_card_next( &card );
  5708. }
  5709. result = snd_ctl_open( &handle, "default", 0 );
  5710. if (result == 0) {
  5711. nDevices++;
  5712. snd_ctl_close( handle );
  5713. }
  5714. return nDevices;
  5715. }
  5716. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  5717. {
  5718. RtAudio::DeviceInfo info;
  5719. info.probed = false;
  5720. unsigned nDevices = 0;
  5721. int result, subdevice, card;
  5722. char name[64];
  5723. snd_ctl_t *chandle;
  5724. // Count cards and devices
  5725. card = -1;
  5726. subdevice = -1;
  5727. snd_card_next( &card );
  5728. while ( card >= 0 ) {
  5729. sprintf( name, "hw:%d", card );
  5730. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  5731. if ( result < 0 ) {
  5732. errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5733. errorText_ = errorStream_.str();
  5734. error( RtAudioError::WARNING );
  5735. goto nextcard;
  5736. }
  5737. subdevice = -1;
  5738. while( 1 ) {
  5739. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  5740. if ( result < 0 ) {
  5741. errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5742. errorText_ = errorStream_.str();
  5743. error( RtAudioError::WARNING );
  5744. break;
  5745. }
  5746. if ( subdevice < 0 ) break;
  5747. if ( nDevices == device ) {
  5748. sprintf( name, "hw:%d,%d", card, subdevice );
  5749. goto foundDevice;
  5750. }
  5751. nDevices++;
  5752. }
  5753. nextcard:
  5754. snd_ctl_close( chandle );
  5755. snd_card_next( &card );
  5756. }
  5757. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  5758. if ( result == 0 ) {
  5759. if ( nDevices == device ) {
  5760. strcpy( name, "default" );
  5761. goto foundDevice;
  5762. }
  5763. nDevices++;
  5764. }
  5765. if ( nDevices == 0 ) {
  5766. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  5767. error( RtAudioError::INVALID_USE );
  5768. return info;
  5769. }
  5770. if ( device >= nDevices ) {
  5771. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  5772. error( RtAudioError::INVALID_USE );
  5773. return info;
  5774. }
  5775. foundDevice:
  5776. // If a stream is already open, we cannot probe the stream devices.
  5777. // Thus, use the saved results.
  5778. if ( stream_.state != STREAM_CLOSED &&
  5779. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  5780. snd_ctl_close( chandle );
  5781. if ( device >= devices_.size() ) {
  5782. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  5783. error( RtAudioError::WARNING );
  5784. return info;
  5785. }
  5786. return devices_[ device ];
  5787. }
  5788. int openMode = SND_PCM_ASYNC;
  5789. snd_pcm_stream_t stream;
  5790. snd_pcm_info_t *pcminfo;
  5791. snd_pcm_info_alloca( &pcminfo );
  5792. snd_pcm_t *phandle;
  5793. snd_pcm_hw_params_t *params;
  5794. snd_pcm_hw_params_alloca( &params );
  5795. // First try for playback unless default device (which has subdev -1)
  5796. stream = SND_PCM_STREAM_PLAYBACK;
  5797. snd_pcm_info_set_stream( pcminfo, stream );
  5798. if ( subdevice != -1 ) {
  5799. snd_pcm_info_set_device( pcminfo, subdevice );
  5800. snd_pcm_info_set_subdevice( pcminfo, 0 );
  5801. result = snd_ctl_pcm_info( chandle, pcminfo );
  5802. if ( result < 0 ) {
  5803. // Device probably doesn't support playback.
  5804. goto captureProbe;
  5805. }
  5806. }
  5807. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  5808. if ( result < 0 ) {
  5809. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  5810. errorText_ = errorStream_.str();
  5811. error( RtAudioError::WARNING );
  5812. goto captureProbe;
  5813. }
  5814. // The device is open ... fill the parameter structure.
  5815. result = snd_pcm_hw_params_any( phandle, params );
  5816. if ( result < 0 ) {
  5817. snd_pcm_close( phandle );
  5818. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  5819. errorText_ = errorStream_.str();
  5820. error( RtAudioError::WARNING );
  5821. goto captureProbe;
  5822. }
  5823. // Get output channel information.
  5824. unsigned int value;
  5825. result = snd_pcm_hw_params_get_channels_max( params, &value );
  5826. if ( result < 0 ) {
  5827. snd_pcm_close( phandle );
  5828. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  5829. errorText_ = errorStream_.str();
  5830. error( RtAudioError::WARNING );
  5831. goto captureProbe;
  5832. }
  5833. info.outputChannels = value;
  5834. snd_pcm_close( phandle );
  5835. captureProbe:
  5836. stream = SND_PCM_STREAM_CAPTURE;
  5837. snd_pcm_info_set_stream( pcminfo, stream );
  5838. // Now try for capture unless default device (with subdev = -1)
  5839. if ( subdevice != -1 ) {
  5840. result = snd_ctl_pcm_info( chandle, pcminfo );
  5841. snd_ctl_close( chandle );
  5842. if ( result < 0 ) {
  5843. // Device probably doesn't support capture.
  5844. if ( info.outputChannels == 0 ) return info;
  5845. goto probeParameters;
  5846. }
  5847. }
  5848. else
  5849. snd_ctl_close( chandle );
  5850. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  5851. if ( result < 0 ) {
  5852. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  5853. errorText_ = errorStream_.str();
  5854. error( RtAudioError::WARNING );
  5855. if ( info.outputChannels == 0 ) return info;
  5856. goto probeParameters;
  5857. }
  5858. // The device is open ... fill the parameter structure.
  5859. result = snd_pcm_hw_params_any( phandle, params );
  5860. if ( result < 0 ) {
  5861. snd_pcm_close( phandle );
  5862. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  5863. errorText_ = errorStream_.str();
  5864. error( RtAudioError::WARNING );
  5865. if ( info.outputChannels == 0 ) return info;
  5866. goto probeParameters;
  5867. }
  5868. result = snd_pcm_hw_params_get_channels_max( params, &value );
  5869. if ( result < 0 ) {
  5870. snd_pcm_close( phandle );
  5871. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  5872. errorText_ = errorStream_.str();
  5873. error( RtAudioError::WARNING );
  5874. if ( info.outputChannels == 0 ) return info;
  5875. goto probeParameters;
  5876. }
  5877. info.inputChannels = value;
  5878. snd_pcm_close( phandle );
  5879. // If device opens for both playback and capture, we determine the channels.
  5880. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  5881. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  5882. // ALSA doesn't provide default devices so we'll use the first available one.
  5883. if ( device == 0 && info.outputChannels > 0 )
  5884. info.isDefaultOutput = true;
  5885. if ( device == 0 && info.inputChannels > 0 )
  5886. info.isDefaultInput = true;
  5887. probeParameters:
  5888. // At this point, we just need to figure out the supported data
  5889. // formats and sample rates. We'll proceed by opening the device in
  5890. // the direction with the maximum number of channels, or playback if
  5891. // they are equal. This might limit our sample rate options, but so
  5892. // be it.
  5893. if ( info.outputChannels >= info.inputChannels )
  5894. stream = SND_PCM_STREAM_PLAYBACK;
  5895. else
  5896. stream = SND_PCM_STREAM_CAPTURE;
  5897. snd_pcm_info_set_stream( pcminfo, stream );
  5898. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  5899. if ( result < 0 ) {
  5900. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  5901. errorText_ = errorStream_.str();
  5902. error( RtAudioError::WARNING );
  5903. return info;
  5904. }
  5905. // The device is open ... fill the parameter structure.
  5906. result = snd_pcm_hw_params_any( phandle, params );
  5907. if ( result < 0 ) {
  5908. snd_pcm_close( phandle );
  5909. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  5910. errorText_ = errorStream_.str();
  5911. error( RtAudioError::WARNING );
  5912. return info;
  5913. }
  5914. // Test our discrete set of sample rate values.
  5915. info.sampleRates.clear();
  5916. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  5917. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {
  5918. info.sampleRates.push_back( SAMPLE_RATES[i] );
  5919. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  5920. info.preferredSampleRate = SAMPLE_RATES[i];
  5921. }
  5922. }
  5923. if ( info.sampleRates.size() == 0 ) {
  5924. snd_pcm_close( phandle );
  5925. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  5926. errorText_ = errorStream_.str();
  5927. error( RtAudioError::WARNING );
  5928. return info;
  5929. }
  5930. // Probe the supported data formats ... we don't care about endian-ness just yet
  5931. snd_pcm_format_t format;
  5932. info.nativeFormats = 0;
  5933. format = SND_PCM_FORMAT_S8;
  5934. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5935. info.nativeFormats |= RTAUDIO_SINT8;
  5936. format = SND_PCM_FORMAT_S16;
  5937. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5938. info.nativeFormats |= RTAUDIO_SINT16;
  5939. format = SND_PCM_FORMAT_S24;
  5940. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5941. info.nativeFormats |= RTAUDIO_SINT24;
  5942. format = SND_PCM_FORMAT_S32;
  5943. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5944. info.nativeFormats |= RTAUDIO_SINT32;
  5945. format = SND_PCM_FORMAT_FLOAT;
  5946. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5947. info.nativeFormats |= RTAUDIO_FLOAT32;
  5948. format = SND_PCM_FORMAT_FLOAT64;
  5949. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  5950. info.nativeFormats |= RTAUDIO_FLOAT64;
  5951. // Check that we have at least one supported format
  5952. if ( info.nativeFormats == 0 ) {
  5953. snd_pcm_close( phandle );
  5954. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  5955. errorText_ = errorStream_.str();
  5956. error( RtAudioError::WARNING );
  5957. return info;
  5958. }
  5959. // Get the device name
  5960. char *cardname;
  5961. result = snd_card_get_name( card, &cardname );
  5962. if ( result >= 0 ) {
  5963. sprintf( name, "hw:%s,%d", cardname, subdevice );
  5964. free( cardname );
  5965. }
  5966. info.name = name;
  5967. // That's all ... close the device and return
  5968. snd_pcm_close( phandle );
  5969. info.probed = true;
  5970. return info;
  5971. }
  5972. void RtApiAlsa :: saveDeviceInfo( void )
  5973. {
  5974. devices_.clear();
  5975. unsigned int nDevices = getDeviceCount();
  5976. devices_.resize( nDevices );
  5977. for ( unsigned int i=0; i<nDevices; i++ )
  5978. devices_[i] = getDeviceInfo( i );
  5979. }
  5980. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  5981. unsigned int firstChannel, unsigned int sampleRate,
  5982. RtAudioFormat format, unsigned int *bufferSize,
  5983. RtAudio::StreamOptions *options )
  5984. {
  5985. #if defined(__RTAUDIO_DEBUG__)
  5986. snd_output_t *out;
  5987. snd_output_stdio_attach(&out, stderr, 0);
  5988. #endif
  5989. // I'm not using the "plug" interface ... too much inconsistent behavior.
  5990. unsigned nDevices = 0;
  5991. int result, subdevice, card;
  5992. char name[64];
  5993. snd_ctl_t *chandle;
  5994. if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )
  5995. snprintf(name, sizeof(name), "%s", "default");
  5996. else {
  5997. // Count cards and devices
  5998. card = -1;
  5999. snd_card_next( &card );
  6000. while ( card >= 0 ) {
  6001. sprintf( name, "hw:%d", card );
  6002. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6003. if ( result < 0 ) {
  6004. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6005. errorText_ = errorStream_.str();
  6006. return FAILURE;
  6007. }
  6008. subdevice = -1;
  6009. while( 1 ) {
  6010. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6011. if ( result < 0 ) break;
  6012. if ( subdevice < 0 ) break;
  6013. if ( nDevices == device ) {
  6014. sprintf( name, "hw:%d,%d", card, subdevice );
  6015. snd_ctl_close( chandle );
  6016. goto foundDevice;
  6017. }
  6018. nDevices++;
  6019. }
  6020. snd_ctl_close( chandle );
  6021. snd_card_next( &card );
  6022. }
  6023. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6024. if ( result == 0 ) {
  6025. if ( nDevices == device ) {
  6026. strcpy( name, "default" );
  6027. goto foundDevice;
  6028. }
  6029. nDevices++;
  6030. }
  6031. if ( nDevices == 0 ) {
  6032. // This should not happen because a check is made before this function is called.
  6033. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  6034. return FAILURE;
  6035. }
  6036. if ( device >= nDevices ) {
  6037. // This should not happen because a check is made before this function is called.
  6038. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  6039. return FAILURE;
  6040. }
  6041. }
  6042. foundDevice:
  6043. // The getDeviceInfo() function will not work for a device that is
  6044. // already open. Thus, we'll probe the system before opening a
  6045. // stream and save the results for use by getDeviceInfo().
  6046. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  6047. this->saveDeviceInfo();
  6048. snd_pcm_stream_t stream;
  6049. if ( mode == OUTPUT )
  6050. stream = SND_PCM_STREAM_PLAYBACK;
  6051. else
  6052. stream = SND_PCM_STREAM_CAPTURE;
  6053. snd_pcm_t *phandle;
  6054. int openMode = SND_PCM_ASYNC;
  6055. result = snd_pcm_open( &phandle, name, stream, openMode );
  6056. if ( result < 0 ) {
  6057. if ( mode == OUTPUT )
  6058. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  6059. else
  6060. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  6061. errorText_ = errorStream_.str();
  6062. return FAILURE;
  6063. }
  6064. // Fill the parameter structure.
  6065. snd_pcm_hw_params_t *hw_params;
  6066. snd_pcm_hw_params_alloca( &hw_params );
  6067. result = snd_pcm_hw_params_any( phandle, hw_params );
  6068. if ( result < 0 ) {
  6069. snd_pcm_close( phandle );
  6070. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  6071. errorText_ = errorStream_.str();
  6072. return FAILURE;
  6073. }
  6074. #if defined(__RTAUDIO_DEBUG__)
  6075. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  6076. snd_pcm_hw_params_dump( hw_params, out );
  6077. #endif
  6078. // Set access ... check user preference.
  6079. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  6080. stream_.userInterleaved = false;
  6081. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6082. if ( result < 0 ) {
  6083. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6084. stream_.deviceInterleaved[mode] = true;
  6085. }
  6086. else
  6087. stream_.deviceInterleaved[mode] = false;
  6088. }
  6089. else {
  6090. stream_.userInterleaved = true;
  6091. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6092. if ( result < 0 ) {
  6093. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6094. stream_.deviceInterleaved[mode] = false;
  6095. }
  6096. else
  6097. stream_.deviceInterleaved[mode] = true;
  6098. }
  6099. if ( result < 0 ) {
  6100. snd_pcm_close( phandle );
  6101. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  6102. errorText_ = errorStream_.str();
  6103. return FAILURE;
  6104. }
  6105. // Determine how to set the device format.
  6106. stream_.userFormat = format;
  6107. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  6108. if ( format == RTAUDIO_SINT8 )
  6109. deviceFormat = SND_PCM_FORMAT_S8;
  6110. else if ( format == RTAUDIO_SINT16 )
  6111. deviceFormat = SND_PCM_FORMAT_S16;
  6112. else if ( format == RTAUDIO_SINT24 )
  6113. deviceFormat = SND_PCM_FORMAT_S24;
  6114. else if ( format == RTAUDIO_SINT32 )
  6115. deviceFormat = SND_PCM_FORMAT_S32;
  6116. else if ( format == RTAUDIO_FLOAT32 )
  6117. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6118. else if ( format == RTAUDIO_FLOAT64 )
  6119. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6120. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  6121. stream_.deviceFormat[mode] = format;
  6122. goto setFormat;
  6123. }
  6124. // The user requested format is not natively supported by the device.
  6125. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6126. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  6127. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  6128. goto setFormat;
  6129. }
  6130. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6131. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6132. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  6133. goto setFormat;
  6134. }
  6135. deviceFormat = SND_PCM_FORMAT_S32;
  6136. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6137. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  6138. goto setFormat;
  6139. }
  6140. deviceFormat = SND_PCM_FORMAT_S24;
  6141. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6142. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  6143. goto setFormat;
  6144. }
  6145. deviceFormat = SND_PCM_FORMAT_S16;
  6146. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6147. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  6148. goto setFormat;
  6149. }
  6150. deviceFormat = SND_PCM_FORMAT_S8;
  6151. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6152. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  6153. goto setFormat;
  6154. }
  6155. // If we get here, no supported format was found.
  6156. snd_pcm_close( phandle );
  6157. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  6158. errorText_ = errorStream_.str();
  6159. return FAILURE;
  6160. setFormat:
  6161. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  6162. if ( result < 0 ) {
  6163. snd_pcm_close( phandle );
  6164. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  6165. errorText_ = errorStream_.str();
  6166. return FAILURE;
  6167. }
  6168. // Determine whether byte-swaping is necessary.
  6169. stream_.doByteSwap[mode] = false;
  6170. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  6171. result = snd_pcm_format_cpu_endian( deviceFormat );
  6172. if ( result == 0 )
  6173. stream_.doByteSwap[mode] = true;
  6174. else if (result < 0) {
  6175. snd_pcm_close( phandle );
  6176. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  6177. errorText_ = errorStream_.str();
  6178. return FAILURE;
  6179. }
  6180. }
  6181. // Set the sample rate.
  6182. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  6183. if ( result < 0 ) {
  6184. snd_pcm_close( phandle );
  6185. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  6186. errorText_ = errorStream_.str();
  6187. return FAILURE;
  6188. }
  6189. // Determine the number of channels for this device. We support a possible
  6190. // minimum device channel number > than the value requested by the user.
  6191. stream_.nUserChannels[mode] = channels;
  6192. unsigned int value;
  6193. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  6194. unsigned int deviceChannels = value;
  6195. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  6196. snd_pcm_close( phandle );
  6197. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  6198. errorText_ = errorStream_.str();
  6199. return FAILURE;
  6200. }
  6201. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  6202. if ( result < 0 ) {
  6203. snd_pcm_close( phandle );
  6204. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6205. errorText_ = errorStream_.str();
  6206. return FAILURE;
  6207. }
  6208. deviceChannels = value;
  6209. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  6210. stream_.nDeviceChannels[mode] = deviceChannels;
  6211. // Set the device channels.
  6212. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  6213. if ( result < 0 ) {
  6214. snd_pcm_close( phandle );
  6215. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6216. errorText_ = errorStream_.str();
  6217. return FAILURE;
  6218. }
  6219. // Set the buffer (or period) size.
  6220. int dir = 0;
  6221. snd_pcm_uframes_t periodSize = *bufferSize;
  6222. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  6223. if ( result < 0 ) {
  6224. snd_pcm_close( phandle );
  6225. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  6226. errorText_ = errorStream_.str();
  6227. return FAILURE;
  6228. }
  6229. *bufferSize = periodSize;
  6230. // Set the buffer number, which in ALSA is referred to as the "period".
  6231. unsigned int periods = 0;
  6232. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  6233. if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
  6234. if ( periods < 2 ) periods = 4; // a fairly safe default value
  6235. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  6236. if ( result < 0 ) {
  6237. snd_pcm_close( phandle );
  6238. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  6239. errorText_ = errorStream_.str();
  6240. return FAILURE;
  6241. }
  6242. // If attempting to setup a duplex stream, the bufferSize parameter
  6243. // MUST be the same in both directions!
  6244. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  6245. snd_pcm_close( phandle );
  6246. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  6247. errorText_ = errorStream_.str();
  6248. return FAILURE;
  6249. }
  6250. stream_.bufferSize = *bufferSize;
  6251. // Install the hardware configuration
  6252. result = snd_pcm_hw_params( phandle, hw_params );
  6253. if ( result < 0 ) {
  6254. snd_pcm_close( phandle );
  6255. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6256. errorText_ = errorStream_.str();
  6257. return FAILURE;
  6258. }
  6259. #if defined(__RTAUDIO_DEBUG__)
  6260. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  6261. snd_pcm_hw_params_dump( hw_params, out );
  6262. #endif
  6263. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  6264. snd_pcm_sw_params_t *sw_params = NULL;
  6265. snd_pcm_sw_params_alloca( &sw_params );
  6266. snd_pcm_sw_params_current( phandle, sw_params );
  6267. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  6268. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  6269. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  6270. // The following two settings were suggested by Theo Veenker
  6271. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  6272. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  6273. // here are two options for a fix
  6274. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  6275. snd_pcm_uframes_t val;
  6276. snd_pcm_sw_params_get_boundary( sw_params, &val );
  6277. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  6278. result = snd_pcm_sw_params( phandle, sw_params );
  6279. if ( result < 0 ) {
  6280. snd_pcm_close( phandle );
  6281. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6282. errorText_ = errorStream_.str();
  6283. return FAILURE;
  6284. }
  6285. #if defined(__RTAUDIO_DEBUG__)
  6286. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  6287. snd_pcm_sw_params_dump( sw_params, out );
  6288. #endif
  6289. // Set flags for buffer conversion
  6290. stream_.doConvertBuffer[mode] = false;
  6291. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  6292. stream_.doConvertBuffer[mode] = true;
  6293. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  6294. stream_.doConvertBuffer[mode] = true;
  6295. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  6296. stream_.nUserChannels[mode] > 1 )
  6297. stream_.doConvertBuffer[mode] = true;
  6298. // Allocate the ApiHandle if necessary and then save.
  6299. AlsaHandle *apiInfo = 0;
  6300. if ( stream_.apiHandle == 0 ) {
  6301. try {
  6302. apiInfo = (AlsaHandle *) new AlsaHandle;
  6303. }
  6304. catch ( std::bad_alloc& ) {
  6305. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  6306. goto error;
  6307. }
  6308. if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
  6309. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  6310. goto error;
  6311. }
  6312. stream_.apiHandle = (void *) apiInfo;
  6313. apiInfo->handles[0] = 0;
  6314. apiInfo->handles[1] = 0;
  6315. }
  6316. else {
  6317. apiInfo = (AlsaHandle *) stream_.apiHandle;
  6318. }
  6319. apiInfo->handles[mode] = phandle;
  6320. phandle = 0;
  6321. // Allocate necessary internal buffers.
  6322. unsigned long bufferBytes;
  6323. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  6324. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  6325. if ( stream_.userBuffer[mode] == NULL ) {
  6326. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  6327. goto error;
  6328. }
  6329. if ( stream_.doConvertBuffer[mode] ) {
  6330. bool makeBuffer = true;
  6331. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  6332. if ( mode == INPUT ) {
  6333. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  6334. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  6335. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  6336. }
  6337. }
  6338. if ( makeBuffer ) {
  6339. bufferBytes *= *bufferSize;
  6340. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  6341. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  6342. if ( stream_.deviceBuffer == NULL ) {
  6343. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  6344. goto error;
  6345. }
  6346. }
  6347. }
  6348. stream_.sampleRate = sampleRate;
  6349. stream_.nBuffers = periods;
  6350. stream_.device[mode] = device;
  6351. stream_.state = STREAM_STOPPED;
  6352. // Setup the buffer conversion information structure.
  6353. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  6354. // Setup thread if necessary.
  6355. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  6356. // We had already set up an output stream.
  6357. stream_.mode = DUPLEX;
  6358. // Link the streams if possible.
  6359. apiInfo->synchronized = false;
  6360. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  6361. apiInfo->synchronized = true;
  6362. else {
  6363. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  6364. error( RtAudioError::WARNING );
  6365. }
  6366. }
  6367. else {
  6368. stream_.mode = mode;
  6369. // Setup callback thread.
  6370. stream_.callbackInfo.object = (void *) this;
  6371. // Set the thread attributes for joinable and realtime scheduling
  6372. // priority (optional). The higher priority will only take affect
  6373. // if the program is run as root or suid. Note, under Linux
  6374. // processes with CAP_SYS_NICE privilege, a user can change
  6375. // scheduling policy and priority (thus need not be root). See
  6376. // POSIX "capabilities".
  6377. pthread_attr_t attr;
  6378. pthread_attr_init( &attr );
  6379. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  6380. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  6381. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  6382. // We previously attempted to increase the audio callback priority
  6383. // to SCHED_RR here via the attributes. However, while no errors
  6384. // were reported in doing so, it did not work. So, now this is
  6385. // done in the alsaCallbackHandler function.
  6386. stream_.callbackInfo.doRealtime = true;
  6387. int priority = options->priority;
  6388. int min = sched_get_priority_min( SCHED_RR );
  6389. int max = sched_get_priority_max( SCHED_RR );
  6390. if ( priority < min ) priority = min;
  6391. else if ( priority > max ) priority = max;
  6392. stream_.callbackInfo.priority = priority;
  6393. }
  6394. #endif
  6395. stream_.callbackInfo.isRunning = true;
  6396. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  6397. pthread_attr_destroy( &attr );
  6398. if ( result ) {
  6399. stream_.callbackInfo.isRunning = false;
  6400. errorText_ = "RtApiAlsa::error creating callback thread!";
  6401. goto error;
  6402. }
  6403. }
  6404. return SUCCESS;
  6405. error:
  6406. if ( apiInfo ) {
  6407. pthread_cond_destroy( &apiInfo->runnable_cv );
  6408. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6409. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6410. delete apiInfo;
  6411. stream_.apiHandle = 0;
  6412. }
  6413. if ( phandle) snd_pcm_close( phandle );
  6414. for ( int i=0; i<2; i++ ) {
  6415. if ( stream_.userBuffer[i] ) {
  6416. free( stream_.userBuffer[i] );
  6417. stream_.userBuffer[i] = 0;
  6418. }
  6419. }
  6420. if ( stream_.deviceBuffer ) {
  6421. free( stream_.deviceBuffer );
  6422. stream_.deviceBuffer = 0;
  6423. }
  6424. stream_.state = STREAM_CLOSED;
  6425. return FAILURE;
  6426. }
  6427. void RtApiAlsa :: closeStream()
  6428. {
  6429. if ( stream_.state == STREAM_CLOSED ) {
  6430. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  6431. error( RtAudioError::WARNING );
  6432. return;
  6433. }
  6434. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6435. stream_.callbackInfo.isRunning = false;
  6436. MUTEX_LOCK( &stream_.mutex );
  6437. if ( stream_.state == STREAM_STOPPED ) {
  6438. apiInfo->runnable = true;
  6439. pthread_cond_signal( &apiInfo->runnable_cv );
  6440. }
  6441. MUTEX_UNLOCK( &stream_.mutex );
  6442. pthread_join( stream_.callbackInfo.thread, NULL );
  6443. if ( stream_.state == STREAM_RUNNING ) {
  6444. stream_.state = STREAM_STOPPED;
  6445. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  6446. snd_pcm_drop( apiInfo->handles[0] );
  6447. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  6448. snd_pcm_drop( apiInfo->handles[1] );
  6449. }
  6450. if ( apiInfo ) {
  6451. pthread_cond_destroy( &apiInfo->runnable_cv );
  6452. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6453. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6454. delete apiInfo;
  6455. stream_.apiHandle = 0;
  6456. }
  6457. for ( int i=0; i<2; i++ ) {
  6458. if ( stream_.userBuffer[i] ) {
  6459. free( stream_.userBuffer[i] );
  6460. stream_.userBuffer[i] = 0;
  6461. }
  6462. }
  6463. if ( stream_.deviceBuffer ) {
  6464. free( stream_.deviceBuffer );
  6465. stream_.deviceBuffer = 0;
  6466. }
  6467. stream_.mode = UNINITIALIZED;
  6468. stream_.state = STREAM_CLOSED;
  6469. }
  6470. void RtApiAlsa :: startStream()
  6471. {
  6472. // This method calls snd_pcm_prepare if the device isn't already in that state.
  6473. verifyStream();
  6474. if ( stream_.state == STREAM_RUNNING ) {
  6475. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  6476. error( RtAudioError::WARNING );
  6477. return;
  6478. }
  6479. MUTEX_LOCK( &stream_.mutex );
  6480. int result = 0;
  6481. snd_pcm_state_t state;
  6482. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6483. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6484. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6485. state = snd_pcm_state( handle[0] );
  6486. if ( state != SND_PCM_STATE_PREPARED ) {
  6487. result = snd_pcm_prepare( handle[0] );
  6488. if ( result < 0 ) {
  6489. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  6490. errorText_ = errorStream_.str();
  6491. goto unlock;
  6492. }
  6493. }
  6494. }
  6495. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6496. result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
  6497. state = snd_pcm_state( handle[1] );
  6498. if ( state != SND_PCM_STATE_PREPARED ) {
  6499. result = snd_pcm_prepare( handle[1] );
  6500. if ( result < 0 ) {
  6501. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  6502. errorText_ = errorStream_.str();
  6503. goto unlock;
  6504. }
  6505. }
  6506. }
  6507. stream_.state = STREAM_RUNNING;
  6508. unlock:
  6509. apiInfo->runnable = true;
  6510. pthread_cond_signal( &apiInfo->runnable_cv );
  6511. MUTEX_UNLOCK( &stream_.mutex );
  6512. if ( result >= 0 ) return;
  6513. error( RtAudioError::SYSTEM_ERROR );
  6514. }
  6515. void RtApiAlsa :: stopStream()
  6516. {
  6517. verifyStream();
  6518. if ( stream_.state == STREAM_STOPPED ) {
  6519. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  6520. error( RtAudioError::WARNING );
  6521. return;
  6522. }
  6523. stream_.state = STREAM_STOPPED;
  6524. MUTEX_LOCK( &stream_.mutex );
  6525. int result = 0;
  6526. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6527. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6528. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6529. if ( apiInfo->synchronized )
  6530. result = snd_pcm_drop( handle[0] );
  6531. else
  6532. result = snd_pcm_drain( handle[0] );
  6533. if ( result < 0 ) {
  6534. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  6535. errorText_ = errorStream_.str();
  6536. goto unlock;
  6537. }
  6538. }
  6539. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6540. result = snd_pcm_drop( handle[1] );
  6541. if ( result < 0 ) {
  6542. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  6543. errorText_ = errorStream_.str();
  6544. goto unlock;
  6545. }
  6546. }
  6547. unlock:
  6548. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6549. MUTEX_UNLOCK( &stream_.mutex );
  6550. if ( result >= 0 ) return;
  6551. error( RtAudioError::SYSTEM_ERROR );
  6552. }
  6553. void RtApiAlsa :: abortStream()
  6554. {
  6555. verifyStream();
  6556. if ( stream_.state == STREAM_STOPPED ) {
  6557. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  6558. error( RtAudioError::WARNING );
  6559. return;
  6560. }
  6561. stream_.state = STREAM_STOPPED;
  6562. MUTEX_LOCK( &stream_.mutex );
  6563. int result = 0;
  6564. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6565. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6566. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6567. result = snd_pcm_drop( handle[0] );
  6568. if ( result < 0 ) {
  6569. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  6570. errorText_ = errorStream_.str();
  6571. goto unlock;
  6572. }
  6573. }
  6574. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6575. result = snd_pcm_drop( handle[1] );
  6576. if ( result < 0 ) {
  6577. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  6578. errorText_ = errorStream_.str();
  6579. goto unlock;
  6580. }
  6581. }
  6582. unlock:
  6583. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6584. MUTEX_UNLOCK( &stream_.mutex );
  6585. if ( result >= 0 ) return;
  6586. error( RtAudioError::SYSTEM_ERROR );
  6587. }
  6588. void RtApiAlsa :: callbackEvent()
  6589. {
  6590. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6591. if ( stream_.state == STREAM_STOPPED ) {
  6592. MUTEX_LOCK( &stream_.mutex );
  6593. while ( !apiInfo->runnable )
  6594. pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
  6595. if ( stream_.state != STREAM_RUNNING ) {
  6596. MUTEX_UNLOCK( &stream_.mutex );
  6597. return;
  6598. }
  6599. MUTEX_UNLOCK( &stream_.mutex );
  6600. }
  6601. if ( stream_.state == STREAM_CLOSED ) {
  6602. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  6603. error( RtAudioError::WARNING );
  6604. return;
  6605. }
  6606. int doStopStream = 0;
  6607. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6608. double streamTime = getStreamTime();
  6609. RtAudioStreamStatus status = 0;
  6610. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  6611. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  6612. apiInfo->xrun[0] = false;
  6613. }
  6614. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  6615. status |= RTAUDIO_INPUT_OVERFLOW;
  6616. apiInfo->xrun[1] = false;
  6617. }
  6618. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  6619. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  6620. if ( doStopStream == 2 ) {
  6621. abortStream();
  6622. return;
  6623. }
  6624. MUTEX_LOCK( &stream_.mutex );
  6625. // The state might change while waiting on a mutex.
  6626. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  6627. int result;
  6628. char *buffer;
  6629. int channels;
  6630. snd_pcm_t **handle;
  6631. snd_pcm_sframes_t frames;
  6632. RtAudioFormat format;
  6633. handle = (snd_pcm_t **) apiInfo->handles;
  6634. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  6635. // Setup parameters.
  6636. if ( stream_.doConvertBuffer[1] ) {
  6637. buffer = stream_.deviceBuffer;
  6638. channels = stream_.nDeviceChannels[1];
  6639. format = stream_.deviceFormat[1];
  6640. }
  6641. else {
  6642. buffer = stream_.userBuffer[1];
  6643. channels = stream_.nUserChannels[1];
  6644. format = stream_.userFormat;
  6645. }
  6646. // Read samples from device in interleaved/non-interleaved format.
  6647. if ( stream_.deviceInterleaved[1] )
  6648. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  6649. else {
  6650. void *bufs[channels];
  6651. size_t offset = stream_.bufferSize * formatBytes( format );
  6652. for ( int i=0; i<channels; i++ )
  6653. bufs[i] = (void *) (buffer + (i * offset));
  6654. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  6655. }
  6656. if ( result < (int) stream_.bufferSize ) {
  6657. // Either an error or overrun occured.
  6658. if ( result == -EPIPE ) {
  6659. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  6660. if ( state == SND_PCM_STATE_XRUN ) {
  6661. apiInfo->xrun[1] = true;
  6662. result = snd_pcm_prepare( handle[1] );
  6663. if ( result < 0 ) {
  6664. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  6665. errorText_ = errorStream_.str();
  6666. }
  6667. }
  6668. else {
  6669. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  6670. errorText_ = errorStream_.str();
  6671. }
  6672. }
  6673. else {
  6674. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  6675. errorText_ = errorStream_.str();
  6676. }
  6677. error( RtAudioError::WARNING );
  6678. goto tryOutput;
  6679. }
  6680. // Do byte swapping if necessary.
  6681. if ( stream_.doByteSwap[1] )
  6682. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  6683. // Do buffer conversion if necessary.
  6684. if ( stream_.doConvertBuffer[1] )
  6685. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  6686. // Check stream latency
  6687. result = snd_pcm_delay( handle[1], &frames );
  6688. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  6689. }
  6690. tryOutput:
  6691. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6692. // Setup parameters and do buffer conversion if necessary.
  6693. if ( stream_.doConvertBuffer[0] ) {
  6694. buffer = stream_.deviceBuffer;
  6695. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  6696. channels = stream_.nDeviceChannels[0];
  6697. format = stream_.deviceFormat[0];
  6698. }
  6699. else {
  6700. buffer = stream_.userBuffer[0];
  6701. channels = stream_.nUserChannels[0];
  6702. format = stream_.userFormat;
  6703. }
  6704. // Do byte swapping if necessary.
  6705. if ( stream_.doByteSwap[0] )
  6706. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  6707. // Write samples to device in interleaved/non-interleaved format.
  6708. if ( stream_.deviceInterleaved[0] )
  6709. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  6710. else {
  6711. void *bufs[channels];
  6712. size_t offset = stream_.bufferSize * formatBytes( format );
  6713. for ( int i=0; i<channels; i++ )
  6714. bufs[i] = (void *) (buffer + (i * offset));
  6715. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  6716. }
  6717. if ( result < (int) stream_.bufferSize ) {
  6718. // Either an error or underrun occured.
  6719. if ( result == -EPIPE ) {
  6720. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  6721. if ( state == SND_PCM_STATE_XRUN ) {
  6722. apiInfo->xrun[0] = true;
  6723. result = snd_pcm_prepare( handle[0] );
  6724. if ( result < 0 ) {
  6725. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  6726. errorText_ = errorStream_.str();
  6727. }
  6728. else
  6729. errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
  6730. }
  6731. else {
  6732. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  6733. errorText_ = errorStream_.str();
  6734. }
  6735. }
  6736. else {
  6737. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  6738. errorText_ = errorStream_.str();
  6739. }
  6740. error( RtAudioError::WARNING );
  6741. goto unlock;
  6742. }
  6743. // Check stream latency
  6744. result = snd_pcm_delay( handle[0], &frames );
  6745. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  6746. }
  6747. unlock:
  6748. MUTEX_UNLOCK( &stream_.mutex );
  6749. RtApi::tickStreamTime();
  6750. if ( doStopStream == 1 ) this->stopStream();
  6751. }
  6752. static void *alsaCallbackHandler( void *ptr )
  6753. {
  6754. CallbackInfo *info = (CallbackInfo *) ptr;
  6755. RtApiAlsa *object = (RtApiAlsa *) info->object;
  6756. bool *isRunning = &info->isRunning;
  6757. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  6758. if ( info->doRealtime ) {
  6759. pthread_t tID = pthread_self(); // ID of this thread
  6760. sched_param prio = { info->priority }; // scheduling priority of thread
  6761. pthread_setschedparam( tID, SCHED_RR, &prio );
  6762. }
  6763. #endif
  6764. while ( *isRunning == true ) {
  6765. pthread_testcancel();
  6766. object->callbackEvent();
  6767. }
  6768. pthread_exit( NULL );
  6769. return NULL;
  6770. }
  6771. //******************** End of __LINUX_ALSA__ *********************//
  6772. #endif
  6773. #if defined(__UNIX_PULSE__)
  6774. // Code written by Peter Meerwald, pmeerw@pmeerw.net
  6775. // and Tristan Matthews.
  6776. #include <pulse/error.h>
  6777. #include <pulse/simple.h>
  6778. #include <cstdio>
  6779. static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
  6780. 44100, 48000, 96000, 0};
  6781. struct rtaudio_pa_format_mapping_t {
  6782. RtAudioFormat rtaudio_format;
  6783. pa_sample_format_t pa_format;
  6784. };
  6785. static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
  6786. {RTAUDIO_SINT16, PA_SAMPLE_S16LE},
  6787. {RTAUDIO_SINT32, PA_SAMPLE_S32LE},
  6788. {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
  6789. {0, PA_SAMPLE_INVALID}};
  6790. struct PulseAudioHandle {
  6791. pa_simple *s_play;
  6792. pa_simple *s_rec;
  6793. pthread_t thread;
  6794. pthread_cond_t runnable_cv;
  6795. bool runnable;
  6796. PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
  6797. };
  6798. RtApiPulse::~RtApiPulse()
  6799. {
  6800. if ( stream_.state != STREAM_CLOSED )
  6801. closeStream();
  6802. }
  6803. unsigned int RtApiPulse::getDeviceCount( void )
  6804. {
  6805. return 1;
  6806. }
  6807. RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
  6808. {
  6809. RtAudio::DeviceInfo info;
  6810. info.probed = true;
  6811. info.name = "PulseAudio";
  6812. info.outputChannels = 2;
  6813. info.inputChannels = 2;
  6814. info.duplexChannels = 2;
  6815. info.isDefaultOutput = true;
  6816. info.isDefaultInput = true;
  6817. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
  6818. info.sampleRates.push_back( *sr );
  6819. info.preferredSampleRate = 48000;
  6820. info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
  6821. return info;
  6822. }
  6823. static void *pulseaudio_callback( void * user )
  6824. {
  6825. CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
  6826. RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
  6827. volatile bool *isRunning = &cbi->isRunning;
  6828. while ( *isRunning ) {
  6829. pthread_testcancel();
  6830. context->callbackEvent();
  6831. }
  6832. pthread_exit( NULL );
  6833. return NULL;
  6834. }
  6835. void RtApiPulse::closeStream( void )
  6836. {
  6837. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6838. stream_.callbackInfo.isRunning = false;
  6839. if ( pah ) {
  6840. MUTEX_LOCK( &stream_.mutex );
  6841. if ( stream_.state == STREAM_STOPPED ) {
  6842. pah->runnable = true;
  6843. pthread_cond_signal( &pah->runnable_cv );
  6844. }
  6845. MUTEX_UNLOCK( &stream_.mutex );
  6846. pthread_join( pah->thread, 0 );
  6847. if ( pah->s_play ) {
  6848. pa_simple_flush( pah->s_play, NULL );
  6849. pa_simple_free( pah->s_play );
  6850. }
  6851. if ( pah->s_rec )
  6852. pa_simple_free( pah->s_rec );
  6853. pthread_cond_destroy( &pah->runnable_cv );
  6854. delete pah;
  6855. stream_.apiHandle = 0;
  6856. }
  6857. if ( stream_.userBuffer[0] ) {
  6858. free( stream_.userBuffer[0] );
  6859. stream_.userBuffer[0] = 0;
  6860. }
  6861. if ( stream_.userBuffer[1] ) {
  6862. free( stream_.userBuffer[1] );
  6863. stream_.userBuffer[1] = 0;
  6864. }
  6865. stream_.state = STREAM_CLOSED;
  6866. stream_.mode = UNINITIALIZED;
  6867. }
  6868. void RtApiPulse::callbackEvent( void )
  6869. {
  6870. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6871. if ( stream_.state == STREAM_STOPPED ) {
  6872. MUTEX_LOCK( &stream_.mutex );
  6873. while ( !pah->runnable )
  6874. pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
  6875. if ( stream_.state != STREAM_RUNNING ) {
  6876. MUTEX_UNLOCK( &stream_.mutex );
  6877. return;
  6878. }
  6879. MUTEX_UNLOCK( &stream_.mutex );
  6880. }
  6881. if ( stream_.state == STREAM_CLOSED ) {
  6882. errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
  6883. "this shouldn't happen!";
  6884. error( RtAudioError::WARNING );
  6885. return;
  6886. }
  6887. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6888. double streamTime = getStreamTime();
  6889. RtAudioStreamStatus status = 0;
  6890. int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
  6891. stream_.bufferSize, streamTime, status,
  6892. stream_.callbackInfo.userData );
  6893. if ( doStopStream == 2 ) {
  6894. abortStream();
  6895. return;
  6896. }
  6897. MUTEX_LOCK( &stream_.mutex );
  6898. void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
  6899. void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
  6900. if ( stream_.state != STREAM_RUNNING )
  6901. goto unlock;
  6902. int pa_error;
  6903. size_t bytes;
  6904. if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6905. if ( stream_.doConvertBuffer[OUTPUT] ) {
  6906. convertBuffer( stream_.deviceBuffer,
  6907. stream_.userBuffer[OUTPUT],
  6908. stream_.convertInfo[OUTPUT] );
  6909. bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
  6910. formatBytes( stream_.deviceFormat[OUTPUT] );
  6911. } else
  6912. bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
  6913. formatBytes( stream_.userFormat );
  6914. if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
  6915. errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
  6916. pa_strerror( pa_error ) << ".";
  6917. errorText_ = errorStream_.str();
  6918. error( RtAudioError::WARNING );
  6919. }
  6920. }
  6921. if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
  6922. if ( stream_.doConvertBuffer[INPUT] )
  6923. bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
  6924. formatBytes( stream_.deviceFormat[INPUT] );
  6925. else
  6926. bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
  6927. formatBytes( stream_.userFormat );
  6928. if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
  6929. errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
  6930. pa_strerror( pa_error ) << ".";
  6931. errorText_ = errorStream_.str();
  6932. error( RtAudioError::WARNING );
  6933. }
  6934. if ( stream_.doConvertBuffer[INPUT] ) {
  6935. convertBuffer( stream_.userBuffer[INPUT],
  6936. stream_.deviceBuffer,
  6937. stream_.convertInfo[INPUT] );
  6938. }
  6939. }
  6940. unlock:
  6941. MUTEX_UNLOCK( &stream_.mutex );
  6942. RtApi::tickStreamTime();
  6943. if ( doStopStream == 1 )
  6944. stopStream();
  6945. }
  6946. void RtApiPulse::startStream( void )
  6947. {
  6948. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6949. if ( stream_.state == STREAM_CLOSED ) {
  6950. errorText_ = "RtApiPulse::startStream(): the stream is not open!";
  6951. error( RtAudioError::INVALID_USE );
  6952. return;
  6953. }
  6954. if ( stream_.state == STREAM_RUNNING ) {
  6955. errorText_ = "RtApiPulse::startStream(): the stream is already running!";
  6956. error( RtAudioError::WARNING );
  6957. return;
  6958. }
  6959. MUTEX_LOCK( &stream_.mutex );
  6960. stream_.state = STREAM_RUNNING;
  6961. pah->runnable = true;
  6962. pthread_cond_signal( &pah->runnable_cv );
  6963. MUTEX_UNLOCK( &stream_.mutex );
  6964. }
  6965. void RtApiPulse::stopStream( void )
  6966. {
  6967. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6968. if ( stream_.state == STREAM_CLOSED ) {
  6969. errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
  6970. error( RtAudioError::INVALID_USE );
  6971. return;
  6972. }
  6973. if ( stream_.state == STREAM_STOPPED ) {
  6974. errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
  6975. error( RtAudioError::WARNING );
  6976. return;
  6977. }
  6978. stream_.state = STREAM_STOPPED;
  6979. MUTEX_LOCK( &stream_.mutex );
  6980. if ( pah && pah->s_play ) {
  6981. int pa_error;
  6982. if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
  6983. errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
  6984. pa_strerror( pa_error ) << ".";
  6985. errorText_ = errorStream_.str();
  6986. MUTEX_UNLOCK( &stream_.mutex );
  6987. error( RtAudioError::SYSTEM_ERROR );
  6988. return;
  6989. }
  6990. }
  6991. stream_.state = STREAM_STOPPED;
  6992. MUTEX_UNLOCK( &stream_.mutex );
  6993. }
  6994. void RtApiPulse::abortStream( void )
  6995. {
  6996. PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
  6997. if ( stream_.state == STREAM_CLOSED ) {
  6998. errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
  6999. error( RtAudioError::INVALID_USE );
  7000. return;
  7001. }
  7002. if ( stream_.state == STREAM_STOPPED ) {
  7003. errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
  7004. error( RtAudioError::WARNING );
  7005. return;
  7006. }
  7007. stream_.state = STREAM_STOPPED;
  7008. MUTEX_LOCK( &stream_.mutex );
  7009. if ( pah && pah->s_play ) {
  7010. int pa_error;
  7011. if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
  7012. errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
  7013. pa_strerror( pa_error ) << ".";
  7014. errorText_ = errorStream_.str();
  7015. MUTEX_UNLOCK( &stream_.mutex );
  7016. error( RtAudioError::SYSTEM_ERROR );
  7017. return;
  7018. }
  7019. }
  7020. stream_.state = STREAM_STOPPED;
  7021. MUTEX_UNLOCK( &stream_.mutex );
  7022. }
  7023. bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
  7024. unsigned int channels, unsigned int firstChannel,
  7025. unsigned int sampleRate, RtAudioFormat format,
  7026. unsigned int *bufferSize, RtAudio::StreamOptions *options )
  7027. {
  7028. PulseAudioHandle *pah = 0;
  7029. unsigned long bufferBytes = 0;
  7030. pa_sample_spec ss;
  7031. if ( device != 0 ) return false;
  7032. if ( mode != INPUT && mode != OUTPUT ) return false;
  7033. if ( channels != 1 && channels != 2 ) {
  7034. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
  7035. return false;
  7036. }
  7037. ss.channels = channels;
  7038. if ( firstChannel != 0 ) return false;
  7039. bool sr_found = false;
  7040. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
  7041. if ( sampleRate == *sr ) {
  7042. sr_found = true;
  7043. stream_.sampleRate = sampleRate;
  7044. ss.rate = sampleRate;
  7045. break;
  7046. }
  7047. }
  7048. if ( !sr_found ) {
  7049. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
  7050. return false;
  7051. }
  7052. bool sf_found = 0;
  7053. for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
  7054. sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
  7055. if ( format == sf->rtaudio_format ) {
  7056. sf_found = true;
  7057. stream_.userFormat = sf->rtaudio_format;
  7058. stream_.deviceFormat[mode] = stream_.userFormat;
  7059. ss.format = sf->pa_format;
  7060. break;
  7061. }
  7062. }
  7063. if ( !sf_found ) { // Use internal data format conversion.
  7064. stream_.userFormat = format;
  7065. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  7066. ss.format = PA_SAMPLE_FLOAT32LE;
  7067. }
  7068. // Set other stream parameters.
  7069. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  7070. else stream_.userInterleaved = true;
  7071. stream_.deviceInterleaved[mode] = true;
  7072. stream_.nBuffers = 1;
  7073. stream_.doByteSwap[mode] = false;
  7074. stream_.nUserChannels[mode] = channels;
  7075. stream_.nDeviceChannels[mode] = channels + firstChannel;
  7076. stream_.channelOffset[mode] = 0;
  7077. std::string streamName = "RtAudio";
  7078. // Set flags for buffer conversion.
  7079. stream_.doConvertBuffer[mode] = false;
  7080. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7081. stream_.doConvertBuffer[mode] = true;
  7082. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7083. stream_.doConvertBuffer[mode] = true;
  7084. // Allocate necessary internal buffers.
  7085. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7086. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7087. if ( stream_.userBuffer[mode] == NULL ) {
  7088. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
  7089. goto error;
  7090. }
  7091. stream_.bufferSize = *bufferSize;
  7092. if ( stream_.doConvertBuffer[mode] ) {
  7093. bool makeBuffer = true;
  7094. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7095. if ( mode == INPUT ) {
  7096. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7097. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7098. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7099. }
  7100. }
  7101. if ( makeBuffer ) {
  7102. bufferBytes *= *bufferSize;
  7103. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7104. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7105. if ( stream_.deviceBuffer == NULL ) {
  7106. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
  7107. goto error;
  7108. }
  7109. }
  7110. }
  7111. stream_.device[mode] = device;
  7112. // Setup the buffer conversion information structure.
  7113. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7114. if ( !stream_.apiHandle ) {
  7115. PulseAudioHandle *pah = new PulseAudioHandle;
  7116. if ( !pah ) {
  7117. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
  7118. goto error;
  7119. }
  7120. stream_.apiHandle = pah;
  7121. if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
  7122. errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
  7123. goto error;
  7124. }
  7125. }
  7126. pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7127. int error;
  7128. if ( options && !options->streamName.empty() ) streamName = options->streamName;
  7129. switch ( mode ) {
  7130. case INPUT:
  7131. pa_buffer_attr buffer_attr;
  7132. buffer_attr.fragsize = bufferBytes;
  7133. buffer_attr.maxlength = -1;
  7134. pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );
  7135. if ( !pah->s_rec ) {
  7136. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
  7137. goto error;
  7138. }
  7139. break;
  7140. case OUTPUT:
  7141. pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );
  7142. if ( !pah->s_play ) {
  7143. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
  7144. goto error;
  7145. }
  7146. break;
  7147. default:
  7148. goto error;
  7149. }
  7150. if ( stream_.mode == UNINITIALIZED )
  7151. stream_.mode = mode;
  7152. else if ( stream_.mode == mode )
  7153. goto error;
  7154. else
  7155. stream_.mode = DUPLEX;
  7156. if ( !stream_.callbackInfo.isRunning ) {
  7157. stream_.callbackInfo.object = this;
  7158. stream_.callbackInfo.isRunning = true;
  7159. if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {
  7160. errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
  7161. goto error;
  7162. }
  7163. }
  7164. stream_.state = STREAM_STOPPED;
  7165. return true;
  7166. error:
  7167. if ( pah && stream_.callbackInfo.isRunning ) {
  7168. pthread_cond_destroy( &pah->runnable_cv );
  7169. delete pah;
  7170. stream_.apiHandle = 0;
  7171. }
  7172. for ( int i=0; i<2; i++ ) {
  7173. if ( stream_.userBuffer[i] ) {
  7174. free( stream_.userBuffer[i] );
  7175. stream_.userBuffer[i] = 0;
  7176. }
  7177. }
  7178. if ( stream_.deviceBuffer ) {
  7179. free( stream_.deviceBuffer );
  7180. stream_.deviceBuffer = 0;
  7181. }
  7182. return FAILURE;
  7183. }
  7184. //******************** End of __UNIX_PULSE__ *********************//
  7185. #endif
  7186. #if defined(__LINUX_OSS__)
  7187. #include <unistd.h>
  7188. #include <sys/ioctl.h>
  7189. #include <unistd.h>
  7190. #include <fcntl.h>
  7191. #include <sys/soundcard.h>
  7192. #include <errno.h>
  7193. #include <math.h>
  7194. static void *ossCallbackHandler(void * ptr);
  7195. // A structure to hold various information related to the OSS API
  7196. // implementation.
  7197. struct OssHandle {
  7198. int id[2]; // device ids
  7199. bool xrun[2];
  7200. bool triggered;
  7201. pthread_cond_t runnable;
  7202. OssHandle()
  7203. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  7204. };
  7205. RtApiOss :: RtApiOss()
  7206. {
  7207. // Nothing to do here.
  7208. }
  7209. RtApiOss :: ~RtApiOss()
  7210. {
  7211. if ( stream_.state != STREAM_CLOSED ) closeStream();
  7212. }
  7213. unsigned int RtApiOss :: getDeviceCount( void )
  7214. {
  7215. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7216. if ( mixerfd == -1 ) {
  7217. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  7218. error( RtAudioError::WARNING );
  7219. return 0;
  7220. }
  7221. oss_sysinfo sysinfo;
  7222. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  7223. close( mixerfd );
  7224. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  7225. error( RtAudioError::WARNING );
  7226. return 0;
  7227. }
  7228. close( mixerfd );
  7229. return sysinfo.numaudios;
  7230. }
  7231. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  7232. {
  7233. RtAudio::DeviceInfo info;
  7234. info.probed = false;
  7235. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7236. if ( mixerfd == -1 ) {
  7237. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  7238. error( RtAudioError::WARNING );
  7239. return info;
  7240. }
  7241. oss_sysinfo sysinfo;
  7242. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7243. if ( result == -1 ) {
  7244. close( mixerfd );
  7245. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  7246. error( RtAudioError::WARNING );
  7247. return info;
  7248. }
  7249. unsigned nDevices = sysinfo.numaudios;
  7250. if ( nDevices == 0 ) {
  7251. close( mixerfd );
  7252. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  7253. error( RtAudioError::INVALID_USE );
  7254. return info;
  7255. }
  7256. if ( device >= nDevices ) {
  7257. close( mixerfd );
  7258. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  7259. error( RtAudioError::INVALID_USE );
  7260. return info;
  7261. }
  7262. oss_audioinfo ainfo;
  7263. ainfo.dev = device;
  7264. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7265. close( mixerfd );
  7266. if ( result == -1 ) {
  7267. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7268. errorText_ = errorStream_.str();
  7269. error( RtAudioError::WARNING );
  7270. return info;
  7271. }
  7272. // Probe channels
  7273. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  7274. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  7275. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  7276. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  7277. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  7278. }
  7279. // Probe data formats ... do for input
  7280. unsigned long mask = ainfo.iformats;
  7281. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  7282. info.nativeFormats |= RTAUDIO_SINT16;
  7283. if ( mask & AFMT_S8 )
  7284. info.nativeFormats |= RTAUDIO_SINT8;
  7285. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  7286. info.nativeFormats |= RTAUDIO_SINT32;
  7287. #ifdef AFMT_FLOAT
  7288. if ( mask & AFMT_FLOAT )
  7289. info.nativeFormats |= RTAUDIO_FLOAT32;
  7290. #endif
  7291. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  7292. info.nativeFormats |= RTAUDIO_SINT24;
  7293. // Check that we have at least one supported format
  7294. if ( info.nativeFormats == 0 ) {
  7295. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7296. errorText_ = errorStream_.str();
  7297. error( RtAudioError::WARNING );
  7298. return info;
  7299. }
  7300. // Probe the supported sample rates.
  7301. info.sampleRates.clear();
  7302. if ( ainfo.nrates ) {
  7303. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  7304. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7305. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  7306. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7307. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7308. info.preferredSampleRate = SAMPLE_RATES[k];
  7309. break;
  7310. }
  7311. }
  7312. }
  7313. }
  7314. else {
  7315. // Check min and max rate values;
  7316. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7317. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {
  7318. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7319. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7320. info.preferredSampleRate = SAMPLE_RATES[k];
  7321. }
  7322. }
  7323. }
  7324. if ( info.sampleRates.size() == 0 ) {
  7325. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  7326. errorText_ = errorStream_.str();
  7327. error( RtAudioError::WARNING );
  7328. }
  7329. else {
  7330. info.probed = true;
  7331. info.name = ainfo.name;
  7332. }
  7333. return info;
  7334. }
  7335. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  7336. unsigned int firstChannel, unsigned int sampleRate,
  7337. RtAudioFormat format, unsigned int *bufferSize,
  7338. RtAudio::StreamOptions *options )
  7339. {
  7340. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7341. if ( mixerfd == -1 ) {
  7342. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  7343. return FAILURE;
  7344. }
  7345. oss_sysinfo sysinfo;
  7346. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7347. if ( result == -1 ) {
  7348. close( mixerfd );
  7349. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  7350. return FAILURE;
  7351. }
  7352. unsigned nDevices = sysinfo.numaudios;
  7353. if ( nDevices == 0 ) {
  7354. // This should not happen because a check is made before this function is called.
  7355. close( mixerfd );
  7356. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  7357. return FAILURE;
  7358. }
  7359. if ( device >= nDevices ) {
  7360. // This should not happen because a check is made before this function is called.
  7361. close( mixerfd );
  7362. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  7363. return FAILURE;
  7364. }
  7365. oss_audioinfo ainfo;
  7366. ainfo.dev = device;
  7367. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7368. close( mixerfd );
  7369. if ( result == -1 ) {
  7370. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7371. errorText_ = errorStream_.str();
  7372. return FAILURE;
  7373. }
  7374. // Check if device supports input or output
  7375. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  7376. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  7377. if ( mode == OUTPUT )
  7378. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  7379. else
  7380. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  7381. errorText_ = errorStream_.str();
  7382. return FAILURE;
  7383. }
  7384. int flags = 0;
  7385. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7386. if ( mode == OUTPUT )
  7387. flags |= O_WRONLY;
  7388. else { // mode == INPUT
  7389. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  7390. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  7391. close( handle->id[0] );
  7392. handle->id[0] = 0;
  7393. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  7394. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  7395. errorText_ = errorStream_.str();
  7396. return FAILURE;
  7397. }
  7398. // Check that the number previously set channels is the same.
  7399. if ( stream_.nUserChannels[0] != channels ) {
  7400. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  7401. errorText_ = errorStream_.str();
  7402. return FAILURE;
  7403. }
  7404. flags |= O_RDWR;
  7405. }
  7406. else
  7407. flags |= O_RDONLY;
  7408. }
  7409. // Set exclusive access if specified.
  7410. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  7411. // Try to open the device.
  7412. int fd;
  7413. fd = open( ainfo.devnode, flags, 0 );
  7414. if ( fd == -1 ) {
  7415. if ( errno == EBUSY )
  7416. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  7417. else
  7418. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  7419. errorText_ = errorStream_.str();
  7420. return FAILURE;
  7421. }
  7422. // For duplex operation, specifically set this mode (this doesn't seem to work).
  7423. /*
  7424. if ( flags | O_RDWR ) {
  7425. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  7426. if ( result == -1) {
  7427. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  7428. errorText_ = errorStream_.str();
  7429. return FAILURE;
  7430. }
  7431. }
  7432. */
  7433. // Check the device channel support.
  7434. stream_.nUserChannels[mode] = channels;
  7435. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  7436. close( fd );
  7437. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  7438. errorText_ = errorStream_.str();
  7439. return FAILURE;
  7440. }
  7441. // Set the number of channels.
  7442. int deviceChannels = channels + firstChannel;
  7443. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  7444. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  7445. close( fd );
  7446. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  7447. errorText_ = errorStream_.str();
  7448. return FAILURE;
  7449. }
  7450. stream_.nDeviceChannels[mode] = deviceChannels;
  7451. // Get the data format mask
  7452. int mask;
  7453. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  7454. if ( result == -1 ) {
  7455. close( fd );
  7456. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  7457. errorText_ = errorStream_.str();
  7458. return FAILURE;
  7459. }
  7460. // Determine how to set the device format.
  7461. stream_.userFormat = format;
  7462. int deviceFormat = -1;
  7463. stream_.doByteSwap[mode] = false;
  7464. if ( format == RTAUDIO_SINT8 ) {
  7465. if ( mask & AFMT_S8 ) {
  7466. deviceFormat = AFMT_S8;
  7467. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7468. }
  7469. }
  7470. else if ( format == RTAUDIO_SINT16 ) {
  7471. if ( mask & AFMT_S16_NE ) {
  7472. deviceFormat = AFMT_S16_NE;
  7473. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7474. }
  7475. else if ( mask & AFMT_S16_OE ) {
  7476. deviceFormat = AFMT_S16_OE;
  7477. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7478. stream_.doByteSwap[mode] = true;
  7479. }
  7480. }
  7481. else if ( format == RTAUDIO_SINT24 ) {
  7482. if ( mask & AFMT_S24_NE ) {
  7483. deviceFormat = AFMT_S24_NE;
  7484. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7485. }
  7486. else if ( mask & AFMT_S24_OE ) {
  7487. deviceFormat = AFMT_S24_OE;
  7488. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7489. stream_.doByteSwap[mode] = true;
  7490. }
  7491. }
  7492. else if ( format == RTAUDIO_SINT32 ) {
  7493. if ( mask & AFMT_S32_NE ) {
  7494. deviceFormat = AFMT_S32_NE;
  7495. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7496. }
  7497. else if ( mask & AFMT_S32_OE ) {
  7498. deviceFormat = AFMT_S32_OE;
  7499. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7500. stream_.doByteSwap[mode] = true;
  7501. }
  7502. }
  7503. if ( deviceFormat == -1 ) {
  7504. // The user requested format is not natively supported by the device.
  7505. if ( mask & AFMT_S16_NE ) {
  7506. deviceFormat = AFMT_S16_NE;
  7507. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7508. }
  7509. else if ( mask & AFMT_S32_NE ) {
  7510. deviceFormat = AFMT_S32_NE;
  7511. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7512. }
  7513. else if ( mask & AFMT_S24_NE ) {
  7514. deviceFormat = AFMT_S24_NE;
  7515. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7516. }
  7517. else if ( mask & AFMT_S16_OE ) {
  7518. deviceFormat = AFMT_S16_OE;
  7519. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7520. stream_.doByteSwap[mode] = true;
  7521. }
  7522. else if ( mask & AFMT_S32_OE ) {
  7523. deviceFormat = AFMT_S32_OE;
  7524. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7525. stream_.doByteSwap[mode] = true;
  7526. }
  7527. else if ( mask & AFMT_S24_OE ) {
  7528. deviceFormat = AFMT_S24_OE;
  7529. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7530. stream_.doByteSwap[mode] = true;
  7531. }
  7532. else if ( mask & AFMT_S8) {
  7533. deviceFormat = AFMT_S8;
  7534. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7535. }
  7536. }
  7537. if ( stream_.deviceFormat[mode] == 0 ) {
  7538. // This really shouldn't happen ...
  7539. close( fd );
  7540. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7541. errorText_ = errorStream_.str();
  7542. return FAILURE;
  7543. }
  7544. // Set the data format.
  7545. int temp = deviceFormat;
  7546. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  7547. if ( result == -1 || deviceFormat != temp ) {
  7548. close( fd );
  7549. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  7550. errorText_ = errorStream_.str();
  7551. return FAILURE;
  7552. }
  7553. // Attempt to set the buffer size. According to OSS, the minimum
  7554. // number of buffers is two. The supposed minimum buffer size is 16
  7555. // bytes, so that will be our lower bound. The argument to this
  7556. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  7557. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  7558. // We'll check the actual value used near the end of the setup
  7559. // procedure.
  7560. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  7561. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  7562. int buffers = 0;
  7563. if ( options ) buffers = options->numberOfBuffers;
  7564. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  7565. if ( buffers < 2 ) buffers = 3;
  7566. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  7567. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  7568. if ( result == -1 ) {
  7569. close( fd );
  7570. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  7571. errorText_ = errorStream_.str();
  7572. return FAILURE;
  7573. }
  7574. stream_.nBuffers = buffers;
  7575. // Save buffer size (in sample frames).
  7576. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  7577. stream_.bufferSize = *bufferSize;
  7578. // Set the sample rate.
  7579. int srate = sampleRate;
  7580. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  7581. if ( result == -1 ) {
  7582. close( fd );
  7583. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  7584. errorText_ = errorStream_.str();
  7585. return FAILURE;
  7586. }
  7587. // Verify the sample rate setup worked.
  7588. if ( abs( srate - (int)sampleRate ) > 100 ) {
  7589. close( fd );
  7590. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  7591. errorText_ = errorStream_.str();
  7592. return FAILURE;
  7593. }
  7594. stream_.sampleRate = sampleRate;
  7595. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  7596. // We're doing duplex setup here.
  7597. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  7598. stream_.nDeviceChannels[0] = deviceChannels;
  7599. }
  7600. // Set interleaving parameters.
  7601. stream_.userInterleaved = true;
  7602. stream_.deviceInterleaved[mode] = true;
  7603. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  7604. stream_.userInterleaved = false;
  7605. // Set flags for buffer conversion
  7606. stream_.doConvertBuffer[mode] = false;
  7607. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7608. stream_.doConvertBuffer[mode] = true;
  7609. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7610. stream_.doConvertBuffer[mode] = true;
  7611. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  7612. stream_.nUserChannels[mode] > 1 )
  7613. stream_.doConvertBuffer[mode] = true;
  7614. // Allocate the stream handles if necessary and then save.
  7615. if ( stream_.apiHandle == 0 ) {
  7616. try {
  7617. handle = new OssHandle;
  7618. }
  7619. catch ( std::bad_alloc& ) {
  7620. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  7621. goto error;
  7622. }
  7623. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  7624. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  7625. goto error;
  7626. }
  7627. stream_.apiHandle = (void *) handle;
  7628. }
  7629. else {
  7630. handle = (OssHandle *) stream_.apiHandle;
  7631. }
  7632. handle->id[mode] = fd;
  7633. // Allocate necessary internal buffers.
  7634. unsigned long bufferBytes;
  7635. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7636. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7637. if ( stream_.userBuffer[mode] == NULL ) {
  7638. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  7639. goto error;
  7640. }
  7641. if ( stream_.doConvertBuffer[mode] ) {
  7642. bool makeBuffer = true;
  7643. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7644. if ( mode == INPUT ) {
  7645. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7646. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7647. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7648. }
  7649. }
  7650. if ( makeBuffer ) {
  7651. bufferBytes *= *bufferSize;
  7652. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7653. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7654. if ( stream_.deviceBuffer == NULL ) {
  7655. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  7656. goto error;
  7657. }
  7658. }
  7659. }
  7660. stream_.device[mode] = device;
  7661. stream_.state = STREAM_STOPPED;
  7662. // Setup the buffer conversion information structure.
  7663. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7664. // Setup thread if necessary.
  7665. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  7666. // We had already set up an output stream.
  7667. stream_.mode = DUPLEX;
  7668. if ( stream_.device[0] == device ) handle->id[0] = fd;
  7669. }
  7670. else {
  7671. stream_.mode = mode;
  7672. // Setup callback thread.
  7673. stream_.callbackInfo.object = (void *) this;
  7674. // Set the thread attributes for joinable and realtime scheduling
  7675. // priority. The higher priority will only take affect if the
  7676. // program is run as root or suid.
  7677. pthread_attr_t attr;
  7678. pthread_attr_init( &attr );
  7679. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  7680. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  7681. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  7682. struct sched_param param;
  7683. int priority = options->priority;
  7684. int min = sched_get_priority_min( SCHED_RR );
  7685. int max = sched_get_priority_max( SCHED_RR );
  7686. if ( priority < min ) priority = min;
  7687. else if ( priority > max ) priority = max;
  7688. param.sched_priority = priority;
  7689. pthread_attr_setschedparam( &attr, &param );
  7690. pthread_attr_setschedpolicy( &attr, SCHED_RR );
  7691. }
  7692. else
  7693. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7694. #else
  7695. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7696. #endif
  7697. stream_.callbackInfo.isRunning = true;
  7698. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  7699. pthread_attr_destroy( &attr );
  7700. if ( result ) {
  7701. stream_.callbackInfo.isRunning = false;
  7702. errorText_ = "RtApiOss::error creating callback thread!";
  7703. goto error;
  7704. }
  7705. }
  7706. return SUCCESS;
  7707. error:
  7708. if ( handle ) {
  7709. pthread_cond_destroy( &handle->runnable );
  7710. if ( handle->id[0] ) close( handle->id[0] );
  7711. if ( handle->id[1] ) close( handle->id[1] );
  7712. delete handle;
  7713. stream_.apiHandle = 0;
  7714. }
  7715. for ( int i=0; i<2; i++ ) {
  7716. if ( stream_.userBuffer[i] ) {
  7717. free( stream_.userBuffer[i] );
  7718. stream_.userBuffer[i] = 0;
  7719. }
  7720. }
  7721. if ( stream_.deviceBuffer ) {
  7722. free( stream_.deviceBuffer );
  7723. stream_.deviceBuffer = 0;
  7724. }
  7725. return FAILURE;
  7726. }
  7727. void RtApiOss :: closeStream()
  7728. {
  7729. if ( stream_.state == STREAM_CLOSED ) {
  7730. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  7731. error( RtAudioError::WARNING );
  7732. return;
  7733. }
  7734. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7735. stream_.callbackInfo.isRunning = false;
  7736. MUTEX_LOCK( &stream_.mutex );
  7737. if ( stream_.state == STREAM_STOPPED )
  7738. pthread_cond_signal( &handle->runnable );
  7739. MUTEX_UNLOCK( &stream_.mutex );
  7740. pthread_join( stream_.callbackInfo.thread, NULL );
  7741. if ( stream_.state == STREAM_RUNNING ) {
  7742. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  7743. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7744. else
  7745. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7746. stream_.state = STREAM_STOPPED;
  7747. }
  7748. if ( handle ) {
  7749. pthread_cond_destroy( &handle->runnable );
  7750. if ( handle->id[0] ) close( handle->id[0] );
  7751. if ( handle->id[1] ) close( handle->id[1] );
  7752. delete handle;
  7753. stream_.apiHandle = 0;
  7754. }
  7755. for ( int i=0; i<2; i++ ) {
  7756. if ( stream_.userBuffer[i] ) {
  7757. free( stream_.userBuffer[i] );
  7758. stream_.userBuffer[i] = 0;
  7759. }
  7760. }
  7761. if ( stream_.deviceBuffer ) {
  7762. free( stream_.deviceBuffer );
  7763. stream_.deviceBuffer = 0;
  7764. }
  7765. stream_.mode = UNINITIALIZED;
  7766. stream_.state = STREAM_CLOSED;
  7767. }
  7768. void RtApiOss :: startStream()
  7769. {
  7770. verifyStream();
  7771. if ( stream_.state == STREAM_RUNNING ) {
  7772. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  7773. error( RtAudioError::WARNING );
  7774. return;
  7775. }
  7776. MUTEX_LOCK( &stream_.mutex );
  7777. stream_.state = STREAM_RUNNING;
  7778. // No need to do anything else here ... OSS automatically starts
  7779. // when fed samples.
  7780. MUTEX_UNLOCK( &stream_.mutex );
  7781. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7782. pthread_cond_signal( &handle->runnable );
  7783. }
  7784. void RtApiOss :: stopStream()
  7785. {
  7786. verifyStream();
  7787. if ( stream_.state == STREAM_STOPPED ) {
  7788. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  7789. error( RtAudioError::WARNING );
  7790. return;
  7791. }
  7792. MUTEX_LOCK( &stream_.mutex );
  7793. // The state might change while waiting on a mutex.
  7794. if ( stream_.state == STREAM_STOPPED ) {
  7795. MUTEX_UNLOCK( &stream_.mutex );
  7796. return;
  7797. }
  7798. int result = 0;
  7799. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7800. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7801. // Flush the output with zeros a few times.
  7802. char *buffer;
  7803. int samples;
  7804. RtAudioFormat format;
  7805. if ( stream_.doConvertBuffer[0] ) {
  7806. buffer = stream_.deviceBuffer;
  7807. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  7808. format = stream_.deviceFormat[0];
  7809. }
  7810. else {
  7811. buffer = stream_.userBuffer[0];
  7812. samples = stream_.bufferSize * stream_.nUserChannels[0];
  7813. format = stream_.userFormat;
  7814. }
  7815. memset( buffer, 0, samples * formatBytes(format) );
  7816. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  7817. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  7818. if ( result == -1 ) {
  7819. errorText_ = "RtApiOss::stopStream: audio write error.";
  7820. error( RtAudioError::WARNING );
  7821. }
  7822. }
  7823. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7824. if ( result == -1 ) {
  7825. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  7826. errorText_ = errorStream_.str();
  7827. goto unlock;
  7828. }
  7829. handle->triggered = false;
  7830. }
  7831. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  7832. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7833. if ( result == -1 ) {
  7834. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  7835. errorText_ = errorStream_.str();
  7836. goto unlock;
  7837. }
  7838. }
  7839. unlock:
  7840. stream_.state = STREAM_STOPPED;
  7841. MUTEX_UNLOCK( &stream_.mutex );
  7842. if ( result != -1 ) return;
  7843. error( RtAudioError::SYSTEM_ERROR );
  7844. }
  7845. void RtApiOss :: abortStream()
  7846. {
  7847. verifyStream();
  7848. if ( stream_.state == STREAM_STOPPED ) {
  7849. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  7850. error( RtAudioError::WARNING );
  7851. return;
  7852. }
  7853. MUTEX_LOCK( &stream_.mutex );
  7854. // The state might change while waiting on a mutex.
  7855. if ( stream_.state == STREAM_STOPPED ) {
  7856. MUTEX_UNLOCK( &stream_.mutex );
  7857. return;
  7858. }
  7859. int result = 0;
  7860. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7861. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7862. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7863. if ( result == -1 ) {
  7864. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  7865. errorText_ = errorStream_.str();
  7866. goto unlock;
  7867. }
  7868. handle->triggered = false;
  7869. }
  7870. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  7871. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7872. if ( result == -1 ) {
  7873. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  7874. errorText_ = errorStream_.str();
  7875. goto unlock;
  7876. }
  7877. }
  7878. unlock:
  7879. stream_.state = STREAM_STOPPED;
  7880. MUTEX_UNLOCK( &stream_.mutex );
  7881. if ( result != -1 ) return;
  7882. error( RtAudioError::SYSTEM_ERROR );
  7883. }
  7884. void RtApiOss :: callbackEvent()
  7885. {
  7886. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7887. if ( stream_.state == STREAM_STOPPED ) {
  7888. MUTEX_LOCK( &stream_.mutex );
  7889. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  7890. if ( stream_.state != STREAM_RUNNING ) {
  7891. MUTEX_UNLOCK( &stream_.mutex );
  7892. return;
  7893. }
  7894. MUTEX_UNLOCK( &stream_.mutex );
  7895. }
  7896. if ( stream_.state == STREAM_CLOSED ) {
  7897. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  7898. error( RtAudioError::WARNING );
  7899. return;
  7900. }
  7901. // Invoke user callback to get fresh output data.
  7902. int doStopStream = 0;
  7903. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7904. double streamTime = getStreamTime();
  7905. RtAudioStreamStatus status = 0;
  7906. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  7907. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  7908. handle->xrun[0] = false;
  7909. }
  7910. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  7911. status |= RTAUDIO_INPUT_OVERFLOW;
  7912. handle->xrun[1] = false;
  7913. }
  7914. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  7915. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  7916. if ( doStopStream == 2 ) {
  7917. this->abortStream();
  7918. return;
  7919. }
  7920. MUTEX_LOCK( &stream_.mutex );
  7921. // The state might change while waiting on a mutex.
  7922. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  7923. int result;
  7924. char *buffer;
  7925. int samples;
  7926. RtAudioFormat format;
  7927. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7928. // Setup parameters and do buffer conversion if necessary.
  7929. if ( stream_.doConvertBuffer[0] ) {
  7930. buffer = stream_.deviceBuffer;
  7931. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  7932. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  7933. format = stream_.deviceFormat[0];
  7934. }
  7935. else {
  7936. buffer = stream_.userBuffer[0];
  7937. samples = stream_.bufferSize * stream_.nUserChannels[0];
  7938. format = stream_.userFormat;
  7939. }
  7940. // Do byte swapping if necessary.
  7941. if ( stream_.doByteSwap[0] )
  7942. byteSwapBuffer( buffer, samples, format );
  7943. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  7944. int trig = 0;
  7945. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  7946. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  7947. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  7948. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  7949. handle->triggered = true;
  7950. }
  7951. else
  7952. // Write samples to device.
  7953. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  7954. if ( result == -1 ) {
  7955. // We'll assume this is an underrun, though there isn't a
  7956. // specific means for determining that.
  7957. handle->xrun[0] = true;
  7958. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  7959. error( RtAudioError::WARNING );
  7960. // Continue on to input section.
  7961. }
  7962. }
  7963. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  7964. // Setup parameters.
  7965. if ( stream_.doConvertBuffer[1] ) {
  7966. buffer = stream_.deviceBuffer;
  7967. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  7968. format = stream_.deviceFormat[1];
  7969. }
  7970. else {
  7971. buffer = stream_.userBuffer[1];
  7972. samples = stream_.bufferSize * stream_.nUserChannels[1];
  7973. format = stream_.userFormat;
  7974. }
  7975. // Read samples from device.
  7976. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  7977. if ( result == -1 ) {
  7978. // We'll assume this is an overrun, though there isn't a
  7979. // specific means for determining that.
  7980. handle->xrun[1] = true;
  7981. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  7982. error( RtAudioError::WARNING );
  7983. goto unlock;
  7984. }
  7985. // Do byte swapping if necessary.
  7986. if ( stream_.doByteSwap[1] )
  7987. byteSwapBuffer( buffer, samples, format );
  7988. // Do buffer conversion if necessary.
  7989. if ( stream_.doConvertBuffer[1] )
  7990. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  7991. }
  7992. unlock:
  7993. MUTEX_UNLOCK( &stream_.mutex );
  7994. RtApi::tickStreamTime();
  7995. if ( doStopStream == 1 ) this->stopStream();
  7996. }
  7997. static void *ossCallbackHandler( void *ptr )
  7998. {
  7999. CallbackInfo *info = (CallbackInfo *) ptr;
  8000. RtApiOss *object = (RtApiOss *) info->object;
  8001. bool *isRunning = &info->isRunning;
  8002. while ( *isRunning == true ) {
  8003. pthread_testcancel();
  8004. object->callbackEvent();
  8005. }
  8006. pthread_exit( NULL );
  8007. return NULL;
  8008. }
  8009. //******************** End of __LINUX_OSS__ *********************//
  8010. #endif
  8011. // *************************************************** //
  8012. //
  8013. // Protected common (OS-independent) RtAudio methods.
  8014. //
  8015. // *************************************************** //
  8016. // This method can be modified to control the behavior of error
  8017. // message printing.
  8018. void RtApi :: error( RtAudioError::Type type )
  8019. {
  8020. errorStream_.str(""); // clear the ostringstream
  8021. RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;
  8022. if ( errorCallback ) {
  8023. // abortStream() can generate new error messages. Ignore them. Just keep original one.
  8024. if ( firstErrorOccurred_ )
  8025. return;
  8026. firstErrorOccurred_ = true;
  8027. const std::string errorMessage = errorText_;
  8028. if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {
  8029. stream_.callbackInfo.isRunning = false; // exit from the thread
  8030. abortStream();
  8031. }
  8032. errorCallback( type, errorMessage );
  8033. firstErrorOccurred_ = false;
  8034. return;
  8035. }
  8036. if ( type == RtAudioError::WARNING && showWarnings_ == true )
  8037. std::cerr << '\n' << errorText_ << "\n\n";
  8038. else if ( type != RtAudioError::WARNING )
  8039. throw( RtAudioError( errorText_, type ) );
  8040. }
  8041. void RtApi :: verifyStream()
  8042. {
  8043. if ( stream_.state == STREAM_CLOSED ) {
  8044. errorText_ = "RtApi:: a stream is not open!";
  8045. error( RtAudioError::INVALID_USE );
  8046. }
  8047. }
  8048. void RtApi :: clearStreamInfo()
  8049. {
  8050. stream_.mode = UNINITIALIZED;
  8051. stream_.state = STREAM_CLOSED;
  8052. stream_.sampleRate = 0;
  8053. stream_.bufferSize = 0;
  8054. stream_.nBuffers = 0;
  8055. stream_.userFormat = 0;
  8056. stream_.userInterleaved = true;
  8057. stream_.streamTime = 0.0;
  8058. stream_.apiHandle = 0;
  8059. stream_.deviceBuffer = 0;
  8060. stream_.callbackInfo.callback = 0;
  8061. stream_.callbackInfo.userData = 0;
  8062. stream_.callbackInfo.isRunning = false;
  8063. stream_.callbackInfo.errorCallback = 0;
  8064. for ( int i=0; i<2; i++ ) {
  8065. stream_.device[i] = 11111;
  8066. stream_.doConvertBuffer[i] = false;
  8067. stream_.deviceInterleaved[i] = true;
  8068. stream_.doByteSwap[i] = false;
  8069. stream_.nUserChannels[i] = 0;
  8070. stream_.nDeviceChannels[i] = 0;
  8071. stream_.channelOffset[i] = 0;
  8072. stream_.deviceFormat[i] = 0;
  8073. stream_.latency[i] = 0;
  8074. stream_.userBuffer[i] = 0;
  8075. stream_.convertInfo[i].channels = 0;
  8076. stream_.convertInfo[i].inJump = 0;
  8077. stream_.convertInfo[i].outJump = 0;
  8078. stream_.convertInfo[i].inFormat = 0;
  8079. stream_.convertInfo[i].outFormat = 0;
  8080. stream_.convertInfo[i].inOffset.clear();
  8081. stream_.convertInfo[i].outOffset.clear();
  8082. }
  8083. }
  8084. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  8085. {
  8086. if ( format == RTAUDIO_SINT16 )
  8087. return 2;
  8088. else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
  8089. return 4;
  8090. else if ( format == RTAUDIO_FLOAT64 )
  8091. return 8;
  8092. else if ( format == RTAUDIO_SINT24 )
  8093. return 3;
  8094. else if ( format == RTAUDIO_SINT8 )
  8095. return 1;
  8096. errorText_ = "RtApi::formatBytes: undefined format.";
  8097. error( RtAudioError::WARNING );
  8098. return 0;
  8099. }
  8100. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  8101. {
  8102. if ( mode == INPUT ) { // convert device to user buffer
  8103. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  8104. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  8105. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  8106. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  8107. }
  8108. else { // convert user to device buffer
  8109. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  8110. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  8111. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  8112. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  8113. }
  8114. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  8115. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  8116. else
  8117. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  8118. // Set up the interleave/deinterleave offsets.
  8119. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  8120. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  8121. ( mode == INPUT && stream_.userInterleaved ) ) {
  8122. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8123. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8124. stream_.convertInfo[mode].outOffset.push_back( k );
  8125. stream_.convertInfo[mode].inJump = 1;
  8126. }
  8127. }
  8128. else {
  8129. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8130. stream_.convertInfo[mode].inOffset.push_back( k );
  8131. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8132. stream_.convertInfo[mode].outJump = 1;
  8133. }
  8134. }
  8135. }
  8136. else { // no (de)interleaving
  8137. if ( stream_.userInterleaved ) {
  8138. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8139. stream_.convertInfo[mode].inOffset.push_back( k );
  8140. stream_.convertInfo[mode].outOffset.push_back( k );
  8141. }
  8142. }
  8143. else {
  8144. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8145. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8146. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8147. stream_.convertInfo[mode].inJump = 1;
  8148. stream_.convertInfo[mode].outJump = 1;
  8149. }
  8150. }
  8151. }
  8152. // Add channel offset.
  8153. if ( firstChannel > 0 ) {
  8154. if ( stream_.deviceInterleaved[mode] ) {
  8155. if ( mode == OUTPUT ) {
  8156. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8157. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  8158. }
  8159. else {
  8160. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8161. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  8162. }
  8163. }
  8164. else {
  8165. if ( mode == OUTPUT ) {
  8166. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8167. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  8168. }
  8169. else {
  8170. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8171. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  8172. }
  8173. }
  8174. }
  8175. }
  8176. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  8177. {
  8178. // This function does format conversion, input/output channel compensation, and
  8179. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  8180. // the lower three bytes of a 32-bit integer.
  8181. // Clear our device buffer when in/out duplex device channels are different
  8182. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  8183. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  8184. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  8185. int j;
  8186. if (info.outFormat == RTAUDIO_FLOAT64) {
  8187. Float64 scale;
  8188. Float64 *out = (Float64 *)outBuffer;
  8189. if (info.inFormat == RTAUDIO_SINT8) {
  8190. signed char *in = (signed char *)inBuffer;
  8191. scale = 1.0 / 127.5;
  8192. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8193. for (j=0; j<info.channels; j++) {
  8194. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8195. out[info.outOffset[j]] += 0.5;
  8196. out[info.outOffset[j]] *= scale;
  8197. }
  8198. in += info.inJump;
  8199. out += info.outJump;
  8200. }
  8201. }
  8202. else if (info.inFormat == RTAUDIO_SINT16) {
  8203. Int16 *in = (Int16 *)inBuffer;
  8204. scale = 1.0 / 32767.5;
  8205. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8206. for (j=0; j<info.channels; j++) {
  8207. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8208. out[info.outOffset[j]] += 0.5;
  8209. out[info.outOffset[j]] *= scale;
  8210. }
  8211. in += info.inJump;
  8212. out += info.outJump;
  8213. }
  8214. }
  8215. else if (info.inFormat == RTAUDIO_SINT24) {
  8216. Int24 *in = (Int24 *)inBuffer;
  8217. scale = 1.0 / 8388607.5;
  8218. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8219. for (j=0; j<info.channels; j++) {
  8220. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());
  8221. out[info.outOffset[j]] += 0.5;
  8222. out[info.outOffset[j]] *= scale;
  8223. }
  8224. in += info.inJump;
  8225. out += info.outJump;
  8226. }
  8227. }
  8228. else if (info.inFormat == RTAUDIO_SINT32) {
  8229. Int32 *in = (Int32 *)inBuffer;
  8230. scale = 1.0 / 2147483647.5;
  8231. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8232. for (j=0; j<info.channels; j++) {
  8233. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8234. out[info.outOffset[j]] += 0.5;
  8235. out[info.outOffset[j]] *= scale;
  8236. }
  8237. in += info.inJump;
  8238. out += info.outJump;
  8239. }
  8240. }
  8241. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8242. Float32 *in = (Float32 *)inBuffer;
  8243. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8244. for (j=0; j<info.channels; j++) {
  8245. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8246. }
  8247. in += info.inJump;
  8248. out += info.outJump;
  8249. }
  8250. }
  8251. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8252. // Channel compensation and/or (de)interleaving only.
  8253. Float64 *in = (Float64 *)inBuffer;
  8254. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8255. for (j=0; j<info.channels; j++) {
  8256. out[info.outOffset[j]] = in[info.inOffset[j]];
  8257. }
  8258. in += info.inJump;
  8259. out += info.outJump;
  8260. }
  8261. }
  8262. }
  8263. else if (info.outFormat == RTAUDIO_FLOAT32) {
  8264. Float32 scale;
  8265. Float32 *out = (Float32 *)outBuffer;
  8266. if (info.inFormat == RTAUDIO_SINT8) {
  8267. signed char *in = (signed char *)inBuffer;
  8268. scale = (Float32) ( 1.0 / 127.5 );
  8269. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8270. for (j=0; j<info.channels; j++) {
  8271. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8272. out[info.outOffset[j]] += 0.5;
  8273. out[info.outOffset[j]] *= scale;
  8274. }
  8275. in += info.inJump;
  8276. out += info.outJump;
  8277. }
  8278. }
  8279. else if (info.inFormat == RTAUDIO_SINT16) {
  8280. Int16 *in = (Int16 *)inBuffer;
  8281. scale = (Float32) ( 1.0 / 32767.5 );
  8282. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8283. for (j=0; j<info.channels; j++) {
  8284. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8285. out[info.outOffset[j]] += 0.5;
  8286. out[info.outOffset[j]] *= scale;
  8287. }
  8288. in += info.inJump;
  8289. out += info.outJump;
  8290. }
  8291. }
  8292. else if (info.inFormat == RTAUDIO_SINT24) {
  8293. Int24 *in = (Int24 *)inBuffer;
  8294. scale = (Float32) ( 1.0 / 8388607.5 );
  8295. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8296. for (j=0; j<info.channels; j++) {
  8297. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());
  8298. out[info.outOffset[j]] += 0.5;
  8299. out[info.outOffset[j]] *= scale;
  8300. }
  8301. in += info.inJump;
  8302. out += info.outJump;
  8303. }
  8304. }
  8305. else if (info.inFormat == RTAUDIO_SINT32) {
  8306. Int32 *in = (Int32 *)inBuffer;
  8307. scale = (Float32) ( 1.0 / 2147483647.5 );
  8308. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8309. for (j=0; j<info.channels; j++) {
  8310. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8311. out[info.outOffset[j]] += 0.5;
  8312. out[info.outOffset[j]] *= scale;
  8313. }
  8314. in += info.inJump;
  8315. out += info.outJump;
  8316. }
  8317. }
  8318. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8319. // Channel compensation and/or (de)interleaving only.
  8320. Float32 *in = (Float32 *)inBuffer;
  8321. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8322. for (j=0; j<info.channels; j++) {
  8323. out[info.outOffset[j]] = in[info.inOffset[j]];
  8324. }
  8325. in += info.inJump;
  8326. out += info.outJump;
  8327. }
  8328. }
  8329. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8330. Float64 *in = (Float64 *)inBuffer;
  8331. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8332. for (j=0; j<info.channels; j++) {
  8333. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8334. }
  8335. in += info.inJump;
  8336. out += info.outJump;
  8337. }
  8338. }
  8339. }
  8340. else if (info.outFormat == RTAUDIO_SINT32) {
  8341. Int32 *out = (Int32 *)outBuffer;
  8342. if (info.inFormat == RTAUDIO_SINT8) {
  8343. signed char *in = (signed char *)inBuffer;
  8344. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8345. for (j=0; j<info.channels; j++) {
  8346. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8347. out[info.outOffset[j]] <<= 24;
  8348. }
  8349. in += info.inJump;
  8350. out += info.outJump;
  8351. }
  8352. }
  8353. else if (info.inFormat == RTAUDIO_SINT16) {
  8354. Int16 *in = (Int16 *)inBuffer;
  8355. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8356. for (j=0; j<info.channels; j++) {
  8357. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8358. out[info.outOffset[j]] <<= 16;
  8359. }
  8360. in += info.inJump;
  8361. out += info.outJump;
  8362. }
  8363. }
  8364. else if (info.inFormat == RTAUDIO_SINT24) {
  8365. Int24 *in = (Int24 *)inBuffer;
  8366. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8367. for (j=0; j<info.channels; j++) {
  8368. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
  8369. out[info.outOffset[j]] <<= 8;
  8370. }
  8371. in += info.inJump;
  8372. out += info.outJump;
  8373. }
  8374. }
  8375. else if (info.inFormat == RTAUDIO_SINT32) {
  8376. // Channel compensation and/or (de)interleaving only.
  8377. Int32 *in = (Int32 *)inBuffer;
  8378. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8379. for (j=0; j<info.channels; j++) {
  8380. out[info.outOffset[j]] = in[info.inOffset[j]];
  8381. }
  8382. in += info.inJump;
  8383. out += info.outJump;
  8384. }
  8385. }
  8386. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8387. Float32 *in = (Float32 *)inBuffer;
  8388. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8389. for (j=0; j<info.channels; j++) {
  8390. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8391. }
  8392. in += info.inJump;
  8393. out += info.outJump;
  8394. }
  8395. }
  8396. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8397. Float64 *in = (Float64 *)inBuffer;
  8398. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8399. for (j=0; j<info.channels; j++) {
  8400. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8401. }
  8402. in += info.inJump;
  8403. out += info.outJump;
  8404. }
  8405. }
  8406. }
  8407. else if (info.outFormat == RTAUDIO_SINT24) {
  8408. Int24 *out = (Int24 *)outBuffer;
  8409. if (info.inFormat == RTAUDIO_SINT8) {
  8410. signed char *in = (signed char *)inBuffer;
  8411. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8412. for (j=0; j<info.channels; j++) {
  8413. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
  8414. //out[info.outOffset[j]] <<= 16;
  8415. }
  8416. in += info.inJump;
  8417. out += info.outJump;
  8418. }
  8419. }
  8420. else if (info.inFormat == RTAUDIO_SINT16) {
  8421. Int16 *in = (Int16 *)inBuffer;
  8422. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8423. for (j=0; j<info.channels; j++) {
  8424. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
  8425. //out[info.outOffset[j]] <<= 8;
  8426. }
  8427. in += info.inJump;
  8428. out += info.outJump;
  8429. }
  8430. }
  8431. else if (info.inFormat == RTAUDIO_SINT24) {
  8432. // Channel compensation and/or (de)interleaving only.
  8433. Int24 *in = (Int24 *)inBuffer;
  8434. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8435. for (j=0; j<info.channels; j++) {
  8436. out[info.outOffset[j]] = in[info.inOffset[j]];
  8437. }
  8438. in += info.inJump;
  8439. out += info.outJump;
  8440. }
  8441. }
  8442. else if (info.inFormat == RTAUDIO_SINT32) {
  8443. Int32 *in = (Int32 *)inBuffer;
  8444. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8445. for (j=0; j<info.channels; j++) {
  8446. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
  8447. //out[info.outOffset[j]] >>= 8;
  8448. }
  8449. in += info.inJump;
  8450. out += info.outJump;
  8451. }
  8452. }
  8453. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8454. Float32 *in = (Float32 *)inBuffer;
  8455. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8456. for (j=0; j<info.channels; j++) {
  8457. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8458. }
  8459. in += info.inJump;
  8460. out += info.outJump;
  8461. }
  8462. }
  8463. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8464. Float64 *in = (Float64 *)inBuffer;
  8465. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8466. for (j=0; j<info.channels; j++) {
  8467. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8468. }
  8469. in += info.inJump;
  8470. out += info.outJump;
  8471. }
  8472. }
  8473. }
  8474. else if (info.outFormat == RTAUDIO_SINT16) {
  8475. Int16 *out = (Int16 *)outBuffer;
  8476. if (info.inFormat == RTAUDIO_SINT8) {
  8477. signed char *in = (signed char *)inBuffer;
  8478. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8479. for (j=0; j<info.channels; j++) {
  8480. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  8481. out[info.outOffset[j]] <<= 8;
  8482. }
  8483. in += info.inJump;
  8484. out += info.outJump;
  8485. }
  8486. }
  8487. else if (info.inFormat == RTAUDIO_SINT16) {
  8488. // Channel compensation and/or (de)interleaving only.
  8489. Int16 *in = (Int16 *)inBuffer;
  8490. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8491. for (j=0; j<info.channels; j++) {
  8492. out[info.outOffset[j]] = in[info.inOffset[j]];
  8493. }
  8494. in += info.inJump;
  8495. out += info.outJump;
  8496. }
  8497. }
  8498. else if (info.inFormat == RTAUDIO_SINT24) {
  8499. Int24 *in = (Int24 *)inBuffer;
  8500. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8501. for (j=0; j<info.channels; j++) {
  8502. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
  8503. }
  8504. in += info.inJump;
  8505. out += info.outJump;
  8506. }
  8507. }
  8508. else if (info.inFormat == RTAUDIO_SINT32) {
  8509. Int32 *in = (Int32 *)inBuffer;
  8510. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8511. for (j=0; j<info.channels; j++) {
  8512. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  8513. }
  8514. in += info.inJump;
  8515. out += info.outJump;
  8516. }
  8517. }
  8518. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8519. Float32 *in = (Float32 *)inBuffer;
  8520. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8521. for (j=0; j<info.channels; j++) {
  8522. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8523. }
  8524. in += info.inJump;
  8525. out += info.outJump;
  8526. }
  8527. }
  8528. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8529. Float64 *in = (Float64 *)inBuffer;
  8530. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8531. for (j=0; j<info.channels; j++) {
  8532. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8533. }
  8534. in += info.inJump;
  8535. out += info.outJump;
  8536. }
  8537. }
  8538. }
  8539. else if (info.outFormat == RTAUDIO_SINT8) {
  8540. signed char *out = (signed char *)outBuffer;
  8541. if (info.inFormat == RTAUDIO_SINT8) {
  8542. // Channel compensation and/or (de)interleaving only.
  8543. signed char *in = (signed char *)inBuffer;
  8544. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8545. for (j=0; j<info.channels; j++) {
  8546. out[info.outOffset[j]] = in[info.inOffset[j]];
  8547. }
  8548. in += info.inJump;
  8549. out += info.outJump;
  8550. }
  8551. }
  8552. if (info.inFormat == RTAUDIO_SINT16) {
  8553. Int16 *in = (Int16 *)inBuffer;
  8554. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8555. for (j=0; j<info.channels; j++) {
  8556. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  8557. }
  8558. in += info.inJump;
  8559. out += info.outJump;
  8560. }
  8561. }
  8562. else if (info.inFormat == RTAUDIO_SINT24) {
  8563. Int24 *in = (Int24 *)inBuffer;
  8564. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8565. for (j=0; j<info.channels; j++) {
  8566. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
  8567. }
  8568. in += info.inJump;
  8569. out += info.outJump;
  8570. }
  8571. }
  8572. else if (info.inFormat == RTAUDIO_SINT32) {
  8573. Int32 *in = (Int32 *)inBuffer;
  8574. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8575. for (j=0; j<info.channels; j++) {
  8576. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  8577. }
  8578. in += info.inJump;
  8579. out += info.outJump;
  8580. }
  8581. }
  8582. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8583. Float32 *in = (Float32 *)inBuffer;
  8584. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8585. for (j=0; j<info.channels; j++) {
  8586. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8587. }
  8588. in += info.inJump;
  8589. out += info.outJump;
  8590. }
  8591. }
  8592. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8593. Float64 *in = (Float64 *)inBuffer;
  8594. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8595. for (j=0; j<info.channels; j++) {
  8596. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8597. }
  8598. in += info.inJump;
  8599. out += info.outJump;
  8600. }
  8601. }
  8602. }
  8603. }
  8604. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  8605. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  8606. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  8607. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  8608. {
  8609. char val;
  8610. char *ptr;
  8611. ptr = buffer;
  8612. if ( format == RTAUDIO_SINT16 ) {
  8613. for ( unsigned int i=0; i<samples; i++ ) {
  8614. // Swap 1st and 2nd bytes.
  8615. val = *(ptr);
  8616. *(ptr) = *(ptr+1);
  8617. *(ptr+1) = val;
  8618. // Increment 2 bytes.
  8619. ptr += 2;
  8620. }
  8621. }
  8622. else if ( format == RTAUDIO_SINT32 ||
  8623. format == RTAUDIO_FLOAT32 ) {
  8624. for ( unsigned int i=0; i<samples; i++ ) {
  8625. // Swap 1st and 4th bytes.
  8626. val = *(ptr);
  8627. *(ptr) = *(ptr+3);
  8628. *(ptr+3) = val;
  8629. // Swap 2nd and 3rd bytes.
  8630. ptr += 1;
  8631. val = *(ptr);
  8632. *(ptr) = *(ptr+1);
  8633. *(ptr+1) = val;
  8634. // Increment 3 more bytes.
  8635. ptr += 3;
  8636. }
  8637. }
  8638. else if ( format == RTAUDIO_SINT24 ) {
  8639. for ( unsigned int i=0; i<samples; i++ ) {
  8640. // Swap 1st and 3rd bytes.
  8641. val = *(ptr);
  8642. *(ptr) = *(ptr+2);
  8643. *(ptr+2) = val;
  8644. // Increment 2 more bytes.
  8645. ptr += 2;
  8646. }
  8647. }
  8648. else if ( format == RTAUDIO_FLOAT64 ) {
  8649. for ( unsigned int i=0; i<samples; i++ ) {
  8650. // Swap 1st and 8th bytes
  8651. val = *(ptr);
  8652. *(ptr) = *(ptr+7);
  8653. *(ptr+7) = val;
  8654. // Swap 2nd and 7th bytes
  8655. ptr += 1;
  8656. val = *(ptr);
  8657. *(ptr) = *(ptr+5);
  8658. *(ptr+5) = val;
  8659. // Swap 3rd and 6th bytes
  8660. ptr += 1;
  8661. val = *(ptr);
  8662. *(ptr) = *(ptr+3);
  8663. *(ptr+3) = val;
  8664. // Swap 4th and 5th bytes
  8665. ptr += 1;
  8666. val = *(ptr);
  8667. *(ptr) = *(ptr+1);
  8668. *(ptr+1) = val;
  8669. // Increment 5 more bytes.
  8670. ptr += 5;
  8671. }
  8672. }
  8673. }
  8674. // Indentation settings for Vim and Emacs
  8675. //
  8676. // Local Variables:
  8677. // c-basic-offset: 2
  8678. // indent-tabs-mode: nil
  8679. // End:
  8680. //
  8681. // vim: et sts=2 sw=2