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__) || defined(__HAIKU__)
  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,
  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. stream_.sampleRate = jackbridge_get_sample_rate( client );
  1791. // Get the latency of the JACK port.
  1792. const char **ports;
  1793. ports = jackbridge_get_ports( client, "system:", NULL, JackPortIsInput );
  1794. if ( ports[ firstChannel ] ) {
  1795. // Added by Ge Wang
  1796. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  1797. // the range (usually the min and max are equal)
  1798. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  1799. // get the latency range
  1800. jackbridge_port_get_latency_range( jackbridge_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  1801. // be optimistic, use the min!
  1802. stream_.latency[mode] = latrange.min;
  1803. //stream_.latency[mode] = jack_port_get_latency( jackbridge_port_by_name( client, ports[ firstChannel ] ) );
  1804. }
  1805. jackbridge_free( ports );
  1806. // The jack server always uses 32-bit floating-point data.
  1807. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1808. stream_.userFormat = format;
  1809. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1810. else stream_.userInterleaved = true;
  1811. // Jack always uses non-interleaved buffers.
  1812. stream_.deviceInterleaved[mode] = false;
  1813. // Jack always provides host byte-ordered data.
  1814. stream_.doByteSwap[mode] = false;
  1815. // Get the buffer size. The buffer size and number of buffers
  1816. // (periods) is set when the jack server is started.
  1817. stream_.bufferSize = (int) jackbridge_get_buffer_size( client );
  1818. *bufferSize = stream_.bufferSize;
  1819. stream_.nDeviceChannels[mode] = channels;
  1820. stream_.nUserChannels[mode] = channels;
  1821. // Set flags for buffer conversion.
  1822. stream_.doConvertBuffer[mode] = false;
  1823. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1824. stream_.doConvertBuffer[mode] = true;
  1825. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  1826. stream_.nUserChannels[mode] > 1 )
  1827. stream_.doConvertBuffer[mode] = true;
  1828. // Allocate our JackHandle structure for the stream.
  1829. if ( handle == 0 ) {
  1830. try {
  1831. handle = new JackHandle;
  1832. }
  1833. catch ( std::bad_alloc& ) {
  1834. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  1835. goto error;
  1836. }
  1837. if ( pthread_cond_init(&handle->condition, NULL) ) {
  1838. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  1839. goto error;
  1840. }
  1841. stream_.apiHandle = (void *) handle;
  1842. handle->client = client;
  1843. }
  1844. // Allocate necessary internal buffers.
  1845. unsigned long bufferBytes;
  1846. bufferBytes = stream_.nUserChannels[mode] * 8192 * formatBytes( stream_.userFormat );
  1847. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1848. if ( stream_.userBuffer[mode] == NULL ) {
  1849. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  1850. goto error;
  1851. }
  1852. if ( stream_.doConvertBuffer[mode] ) {
  1853. bool makeBuffer = true;
  1854. if ( mode == OUTPUT )
  1855. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1856. else { // mode == INPUT
  1857. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  1858. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1859. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  1860. if ( bufferBytes < bytesOut ) makeBuffer = false;
  1861. }
  1862. }
  1863. if ( makeBuffer ) {
  1864. bufferBytes *= 8192;
  1865. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1866. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1867. if ( stream_.deviceBuffer == NULL ) {
  1868. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  1869. goto error;
  1870. }
  1871. }
  1872. }
  1873. // Allocate memory for the Jack ports (channels) identifiers.
  1874. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  1875. if ( handle->ports[mode] == NULL ) {
  1876. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  1877. goto error;
  1878. }
  1879. stream_.device[mode] = device;
  1880. stream_.channelOffset[mode] = firstChannel;
  1881. stream_.state = STREAM_STOPPED;
  1882. stream_.callbackInfo.object = (void *) this;
  1883. if ( stream_.mode == OUTPUT && mode == INPUT )
  1884. // We had already set up the stream for output.
  1885. stream_.mode = DUPLEX;
  1886. else {
  1887. stream_.mode = mode;
  1888. jackbridge_set_buffer_size_callback( handle->client, jackBufferSizeHandler, (void *) &stream_.callbackInfo );
  1889. jackbridge_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  1890. jackbridge_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
  1891. jackbridge_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  1892. }
  1893. // Register our ports.
  1894. char label[64];
  1895. if ( mode == OUTPUT ) {
  1896. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1897. snprintf( label, 64, "audio-out%d", i+1 );
  1898. handle->ports[0][i] = jackbridge_port_register( handle->client, (const char *)label,
  1899. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  1900. }
  1901. }
  1902. else {
  1903. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1904. snprintf( label, 64, "audio-in%d", i+1 );
  1905. handle->ports[1][i] = jackbridge_port_register( handle->client, (const char *)label,
  1906. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  1907. }
  1908. }
  1909. // auto-connect-off "device" is at index 1
  1910. shouldAutoconnect_ = (device != 1 &&
  1911. std::getenv("LADISH_APP_NAME") == nullptr &&
  1912. std::getenv("NSM_URL") == nullptr);
  1913. // Setup the buffer conversion information structure. We don't use
  1914. // buffers to do channel offsets, so we override that parameter
  1915. // here.
  1916. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  1917. if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
  1918. return SUCCESS;
  1919. error:
  1920. if ( handle ) {
  1921. pthread_cond_destroy( &handle->condition );
  1922. jackbridge_client_close( handle->client );
  1923. if ( handle->ports[0] ) free( handle->ports[0] );
  1924. if ( handle->ports[1] ) free( handle->ports[1] );
  1925. delete handle;
  1926. stream_.apiHandle = 0;
  1927. }
  1928. for ( int i=0; i<2; i++ ) {
  1929. if ( stream_.userBuffer[i] ) {
  1930. free( stream_.userBuffer[i] );
  1931. stream_.userBuffer[i] = 0;
  1932. }
  1933. }
  1934. if ( stream_.deviceBuffer ) {
  1935. free( stream_.deviceBuffer );
  1936. stream_.deviceBuffer = 0;
  1937. }
  1938. return FAILURE;
  1939. }
  1940. void RtApiJack :: closeStream( void )
  1941. {
  1942. if ( stream_.state == STREAM_CLOSED ) {
  1943. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  1944. error( RtAudioError::WARNING );
  1945. return;
  1946. }
  1947. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1948. if ( handle ) {
  1949. if ( stream_.state == STREAM_RUNNING )
  1950. jackbridge_deactivate( handle->client );
  1951. jackbridge_client_close( handle->client );
  1952. }
  1953. if ( handle ) {
  1954. if ( handle->ports[0] ) free( handle->ports[0] );
  1955. if ( handle->ports[1] ) free( handle->ports[1] );
  1956. pthread_cond_destroy( &handle->condition );
  1957. delete handle;
  1958. stream_.apiHandle = 0;
  1959. }
  1960. for ( int i=0; i<2; i++ ) {
  1961. if ( stream_.userBuffer[i] ) {
  1962. free( stream_.userBuffer[i] );
  1963. stream_.userBuffer[i] = 0;
  1964. }
  1965. }
  1966. if ( stream_.deviceBuffer ) {
  1967. free( stream_.deviceBuffer );
  1968. stream_.deviceBuffer = 0;
  1969. }
  1970. stream_.mode = UNINITIALIZED;
  1971. stream_.state = STREAM_CLOSED;
  1972. }
  1973. void RtApiJack :: startStream( void )
  1974. {
  1975. verifyStream();
  1976. if ( stream_.state == STREAM_RUNNING ) {
  1977. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  1978. error( RtAudioError::WARNING );
  1979. return;
  1980. }
  1981. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1982. bool result = jackbridge_activate( handle->client );
  1983. if ( ! result ) {
  1984. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  1985. goto unlock;
  1986. }
  1987. const char **ports;
  1988. // Get the list of available ports.
  1989. if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
  1990. result = false;
  1991. ports = jackbridge_get_ports( handle->client, "system:", NULL, JackPortIsInput);
  1992. if ( ports == NULL) {
  1993. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  1994. goto unlock;
  1995. }
  1996. // Now make the port connections. Since RtAudio wasn't designed to
  1997. // allow the user to select particular channels of a device, we'll
  1998. // just open the first "nChannels" ports with offset.
  1999. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2000. result = false;
  2001. if ( ports[ stream_.channelOffset[0] + i ] )
  2002. result = jackbridge_connect( handle->client, jackbridge_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2003. if ( ! result ) {
  2004. jackbridge_free( ports );
  2005. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2006. goto unlock;
  2007. }
  2008. }
  2009. jackbridge_free(ports);
  2010. }
  2011. if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
  2012. result = false;
  2013. ports = jackbridge_get_ports( handle->client, "system:", NULL, JackPortIsOutput );
  2014. if ( ports == NULL) {
  2015. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2016. goto unlock;
  2017. }
  2018. // Now make the port connections. See note above.
  2019. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2020. result = false;
  2021. if ( ports[ stream_.channelOffset[1] + i ] )
  2022. result = jackbridge_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jackbridge_port_name( handle->ports[1][i] ) );
  2023. if ( ! result ) {
  2024. jackbridge_free( ports );
  2025. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2026. goto unlock;
  2027. }
  2028. }
  2029. jackbridge_free(ports);
  2030. }
  2031. handle->drainCounter = 0;
  2032. handle->internalDrain = false;
  2033. stream_.state = STREAM_RUNNING;
  2034. unlock:
  2035. if ( result ) return;
  2036. error( RtAudioError::SYSTEM_ERROR );
  2037. }
  2038. void RtApiJack :: stopStream( void )
  2039. {
  2040. verifyStream();
  2041. if ( stream_.state == STREAM_STOPPED ) {
  2042. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2043. error( RtAudioError::WARNING );
  2044. return;
  2045. }
  2046. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2047. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2048. if ( handle->drainCounter == 0 ) {
  2049. handle->drainCounter = 2;
  2050. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2051. }
  2052. }
  2053. jackbridge_deactivate( handle->client );
  2054. stream_.state = STREAM_STOPPED;
  2055. }
  2056. void RtApiJack :: abortStream( void )
  2057. {
  2058. verifyStream();
  2059. if ( stream_.state == STREAM_STOPPED ) {
  2060. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2061. error( RtAudioError::WARNING );
  2062. return;
  2063. }
  2064. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2065. handle->drainCounter = 2;
  2066. stopStream();
  2067. }
  2068. // This function will be called by a spawned thread when the user
  2069. // callback function signals that the stream should be stopped or
  2070. // aborted. It is necessary to handle it this way because the
  2071. // callbackEvent() function must return before the jackbridge_deactivate()
  2072. // function will return.
  2073. static void *jackStopStream( void *ptr )
  2074. {
  2075. CallbackInfo *info = (CallbackInfo *) ptr;
  2076. RtApiJack *object = (RtApiJack *) info->object;
  2077. object->stopStream();
  2078. pthread_exit( NULL );
  2079. return NULL;
  2080. }
  2081. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2082. {
  2083. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2084. if ( stream_.state == STREAM_CLOSED ) {
  2085. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2086. error( RtAudioError::WARNING );
  2087. return FAILURE;
  2088. }
  2089. if ( nframes > 8192 ) {
  2090. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size is too big ... cannot process!";
  2091. error( RtAudioError::WARNING );
  2092. return FAILURE;
  2093. }
  2094. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2095. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2096. // Check if we were draining the stream and signal is finished.
  2097. if ( handle->drainCounter > 3 ) {
  2098. ThreadHandle threadId;
  2099. stream_.state = STREAM_STOPPING;
  2100. if ( handle->internalDrain == true )
  2101. pthread_create( &threadId, NULL, jackStopStream, info );
  2102. else
  2103. pthread_cond_signal( &handle->condition );
  2104. return SUCCESS;
  2105. }
  2106. // Invoke user callback first, to get fresh output data.
  2107. if ( handle->drainCounter == 0 ) {
  2108. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2109. double streamTime = getStreamTime();
  2110. RtAudioStreamStatus status = 0;
  2111. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2112. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2113. handle->xrun[0] = false;
  2114. }
  2115. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2116. status |= RTAUDIO_INPUT_OVERFLOW;
  2117. handle->xrun[1] = false;
  2118. }
  2119. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2120. nframes, streamTime, status, info->userData );
  2121. if ( cbReturnValue == 2 ) {
  2122. stream_.state = STREAM_STOPPING;
  2123. handle->drainCounter = 2;
  2124. ThreadHandle id;
  2125. pthread_create( &id, NULL, jackStopStream, info );
  2126. return SUCCESS;
  2127. }
  2128. else if ( cbReturnValue == 1 ) {
  2129. handle->drainCounter = 1;
  2130. handle->internalDrain = true;
  2131. }
  2132. }
  2133. jack_default_audio_sample_t *jackbuffer;
  2134. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2135. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2136. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2137. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2138. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2139. memset( jackbuffer, 0, bufferBytes );
  2140. }
  2141. }
  2142. else if ( stream_.doConvertBuffer[0] ) {
  2143. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2144. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2145. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2146. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2147. }
  2148. }
  2149. else { // no buffer conversion
  2150. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2151. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2152. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2153. }
  2154. }
  2155. }
  2156. // Don't bother draining input
  2157. if ( handle->drainCounter ) {
  2158. handle->drainCounter++;
  2159. goto unlock;
  2160. }
  2161. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2162. if ( stream_.doConvertBuffer[1] ) {
  2163. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2164. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2165. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2166. }
  2167. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2168. }
  2169. else { // no buffer conversion
  2170. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2171. jackbuffer = (jack_default_audio_sample_t *) jackbridge_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2172. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2173. }
  2174. }
  2175. }
  2176. unlock:
  2177. RtApi::tickStreamTime();
  2178. return SUCCESS;
  2179. }
  2180. bool RtApiJack :: bufferSizeEvent( unsigned long nframes )
  2181. {
  2182. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2183. if ( stream_.state == STREAM_CLOSED ) {
  2184. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2185. error( RtAudioError::WARNING );
  2186. return FAILURE;
  2187. }
  2188. if ( nframes > 8192 ) {
  2189. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size is too big ... cannot process!";
  2190. error( RtAudioError::WARNING );
  2191. return FAILURE;
  2192. }
  2193. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2194. RtAudioBufferSizeCallback callback = (RtAudioBufferSizeCallback) info->bufSizeCallback;
  2195. return callback( nframes, info->userData );
  2196. }
  2197. //******************** End of __UNIX_JACK__ *********************//
  2198. #endif
  2199. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2200. // The ASIO API is designed around a callback scheme, so this
  2201. // implementation is similar to that used for OS-X CoreAudio and Linux
  2202. // Jack. The primary constraint with ASIO is that it only allows
  2203. // access to a single driver at a time. Thus, it is not possible to
  2204. // have more than one simultaneous RtAudio stream.
  2205. //
  2206. // This implementation also requires a number of external ASIO files
  2207. // and a few global variables. The ASIO callback scheme does not
  2208. // allow for the passing of user data, so we must create a global
  2209. // pointer to our callbackInfo structure.
  2210. //
  2211. // On unix systems, we make use of a pthread condition variable.
  2212. // Since there is no equivalent in Windows, I hacked something based
  2213. // on information found in
  2214. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2215. #include "asio.cpp"
  2216. #include "asiodrivers.cpp"
  2217. #include "asiolist.cpp"
  2218. #include "iasiothiscallresolver.cpp"
  2219. #include <cmath>
  2220. static AsioDrivers drivers;
  2221. static ASIOCallbacks asioCallbacks;
  2222. static ASIODriverInfo driverInfo;
  2223. static CallbackInfo *asioCallbackInfo;
  2224. static bool asioXRun;
  2225. struct AsioHandle {
  2226. int drainCounter; // Tracks callback counts when draining
  2227. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2228. ASIOBufferInfo *bufferInfos;
  2229. HANDLE condition;
  2230. AsioHandle()
  2231. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2232. };
  2233. // Function declarations (definitions at end of section)
  2234. static const char* getAsioErrorString( ASIOError result );
  2235. static void sampleRateChanged( ASIOSampleRate sRate );
  2236. static long asioMessages( long selector, long value, void* message, double* opt );
  2237. RtApiAsio :: RtApiAsio()
  2238. {
  2239. // ASIO cannot run on a multi-threaded appartment. You can call
  2240. // CoInitialize beforehand, but it must be for appartment threading
  2241. // (in which case, CoInitilialize will return S_FALSE here).
  2242. coInitialized_ = false;
  2243. HRESULT hr = CoInitialize( NULL );
  2244. if ( FAILED(hr) ) {
  2245. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2246. error( RtAudioError::WARNING );
  2247. }
  2248. coInitialized_ = true;
  2249. drivers.removeCurrentDriver();
  2250. driverInfo.asioVersion = 2;
  2251. // See note in DirectSound implementation about GetDesktopWindow().
  2252. driverInfo.sysRef = GetForegroundWindow();
  2253. }
  2254. RtApiAsio :: ~RtApiAsio()
  2255. {
  2256. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2257. if ( coInitialized_ ) CoUninitialize();
  2258. }
  2259. unsigned int RtApiAsio :: getDeviceCount( void )
  2260. {
  2261. return (unsigned int) drivers.asioGetNumDev();
  2262. }
  2263. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2264. {
  2265. RtAudio::DeviceInfo info;
  2266. info.probed = false;
  2267. // Get device ID
  2268. unsigned int nDevices = getDeviceCount();
  2269. if ( nDevices == 0 ) {
  2270. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2271. error( RtAudioError::INVALID_USE );
  2272. return info;
  2273. }
  2274. if ( device >= nDevices ) {
  2275. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2276. error( RtAudioError::INVALID_USE );
  2277. return info;
  2278. }
  2279. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2280. if ( stream_.state != STREAM_CLOSED ) {
  2281. if ( device >= devices_.size() ) {
  2282. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2283. error( RtAudioError::WARNING );
  2284. return info;
  2285. }
  2286. return devices_[ device ];
  2287. }
  2288. char driverName[32];
  2289. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2290. if ( result != ASE_OK ) {
  2291. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2292. errorText_ = errorStream_.str();
  2293. error( RtAudioError::WARNING );
  2294. return info;
  2295. }
  2296. info.name = driverName;
  2297. if ( !drivers.loadDriver( driverName ) ) {
  2298. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2299. errorText_ = errorStream_.str();
  2300. error( RtAudioError::WARNING );
  2301. return info;
  2302. }
  2303. result = ASIOInit( &driverInfo );
  2304. if ( result != ASE_OK ) {
  2305. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2306. errorText_ = errorStream_.str();
  2307. error( RtAudioError::WARNING );
  2308. return info;
  2309. }
  2310. // Determine the device channel information.
  2311. long inputChannels, outputChannels;
  2312. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2313. if ( result != ASE_OK ) {
  2314. drivers.removeCurrentDriver();
  2315. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2316. errorText_ = errorStream_.str();
  2317. error( RtAudioError::WARNING );
  2318. return info;
  2319. }
  2320. info.outputChannels = outputChannels;
  2321. info.inputChannels = inputChannels;
  2322. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2323. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2324. // Determine the supported sample rates.
  2325. info.sampleRates.clear();
  2326. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2327. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2328. if ( result == ASE_OK ) {
  2329. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2330. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  2331. info.preferredSampleRate = SAMPLE_RATES[i];
  2332. }
  2333. }
  2334. // Determine supported data types ... just check first channel and assume rest are the same.
  2335. ASIOChannelInfo channelInfo;
  2336. channelInfo.channel = 0;
  2337. channelInfo.isInput = true;
  2338. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2339. result = ASIOGetChannelInfo( &channelInfo );
  2340. if ( result != ASE_OK ) {
  2341. drivers.removeCurrentDriver();
  2342. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2343. errorText_ = errorStream_.str();
  2344. error( RtAudioError::WARNING );
  2345. return info;
  2346. }
  2347. info.nativeFormats = 0;
  2348. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2349. info.nativeFormats |= RTAUDIO_SINT16;
  2350. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2351. info.nativeFormats |= RTAUDIO_SINT32;
  2352. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2353. info.nativeFormats |= RTAUDIO_FLOAT32;
  2354. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2355. info.nativeFormats |= RTAUDIO_FLOAT64;
  2356. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2357. info.nativeFormats |= RTAUDIO_SINT24;
  2358. if ( info.outputChannels > 0 )
  2359. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2360. if ( info.inputChannels > 0 )
  2361. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2362. info.probed = true;
  2363. drivers.removeCurrentDriver();
  2364. return info;
  2365. }
  2366. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2367. {
  2368. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2369. object->callbackEvent( index );
  2370. }
  2371. void RtApiAsio :: saveDeviceInfo( void )
  2372. {
  2373. devices_.clear();
  2374. unsigned int nDevices = getDeviceCount();
  2375. devices_.resize( nDevices );
  2376. for ( unsigned int i=0; i<nDevices; i++ )
  2377. devices_[i] = getDeviceInfo( i );
  2378. }
  2379. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2380. unsigned int firstChannel, unsigned int sampleRate,
  2381. RtAudioFormat format, unsigned int *bufferSize,
  2382. RtAudio::StreamOptions *options )
  2383. {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2384. bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
  2385. // For ASIO, a duplex stream MUST use the same driver.
  2386. if ( isDuplexInput && stream_.device[0] != device ) {
  2387. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2388. return FAILURE;
  2389. }
  2390. char driverName[32];
  2391. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2392. if ( result != ASE_OK ) {
  2393. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2394. errorText_ = errorStream_.str();
  2395. return FAILURE;
  2396. }
  2397. // Only load the driver once for duplex stream.
  2398. if ( !isDuplexInput ) {
  2399. // The getDeviceInfo() function will not work when a stream is open
  2400. // because ASIO does not allow multiple devices to run at the same
  2401. // time. Thus, we'll probe the system before opening a stream and
  2402. // save the results for use by getDeviceInfo().
  2403. this->saveDeviceInfo();
  2404. if ( !drivers.loadDriver( driverName ) ) {
  2405. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2406. errorText_ = errorStream_.str();
  2407. return FAILURE;
  2408. }
  2409. result = ASIOInit( &driverInfo );
  2410. if ( result != ASE_OK ) {
  2411. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2412. errorText_ = errorStream_.str();
  2413. return FAILURE;
  2414. }
  2415. }
  2416. // keep them before any "goto error", they are used for error cleanup + goto device boundary checks
  2417. bool buffersAllocated = false;
  2418. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2419. unsigned int nChannels;
  2420. // Check the device channel count.
  2421. long inputChannels, outputChannels;
  2422. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2423. if ( result != ASE_OK ) {
  2424. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2425. errorText_ = errorStream_.str();
  2426. goto error;
  2427. }
  2428. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2429. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2430. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2431. errorText_ = errorStream_.str();
  2432. goto error;
  2433. }
  2434. stream_.nDeviceChannels[mode] = channels;
  2435. stream_.nUserChannels[mode] = channels;
  2436. stream_.channelOffset[mode] = firstChannel;
  2437. // Verify the sample rate is supported.
  2438. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2439. if ( result != ASE_OK ) {
  2440. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2441. errorText_ = errorStream_.str();
  2442. goto error;
  2443. }
  2444. // Get the current sample rate
  2445. ASIOSampleRate currentRate;
  2446. result = ASIOGetSampleRate( &currentRate );
  2447. if ( result != ASE_OK ) {
  2448. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2449. errorText_ = errorStream_.str();
  2450. goto error;
  2451. }
  2452. // Set the sample rate only if necessary
  2453. if ( currentRate != sampleRate ) {
  2454. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2455. if ( result != ASE_OK ) {
  2456. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2457. errorText_ = errorStream_.str();
  2458. goto error;
  2459. }
  2460. }
  2461. // Determine the driver data type.
  2462. ASIOChannelInfo channelInfo;
  2463. channelInfo.channel = 0;
  2464. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2465. else channelInfo.isInput = true;
  2466. result = ASIOGetChannelInfo( &channelInfo );
  2467. if ( result != ASE_OK ) {
  2468. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2469. errorText_ = errorStream_.str();
  2470. goto error;
  2471. }
  2472. // Assuming WINDOWS host is always little-endian.
  2473. stream_.doByteSwap[mode] = false;
  2474. stream_.userFormat = format;
  2475. stream_.deviceFormat[mode] = 0;
  2476. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2477. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2478. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2479. }
  2480. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2481. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2482. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2483. }
  2484. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2485. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2486. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2487. }
  2488. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2489. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2490. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2491. }
  2492. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2493. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2494. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2495. }
  2496. if ( stream_.deviceFormat[mode] == 0 ) {
  2497. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2498. errorText_ = errorStream_.str();
  2499. goto error;
  2500. }
  2501. // Set the buffer size. For a duplex stream, this will end up
  2502. // setting the buffer size based on the input constraints, which
  2503. // should be ok.
  2504. long minSize, maxSize, preferSize, granularity;
  2505. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2506. if ( result != ASE_OK ) {
  2507. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2508. errorText_ = errorStream_.str();
  2509. goto error;
  2510. }
  2511. if ( isDuplexInput ) {
  2512. // When this is the duplex input (output was opened before), then we have to use the same
  2513. // buffersize as the output, because it might use the preferred buffer size, which most
  2514. // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
  2515. // So instead of throwing an error, make them equal. The caller uses the reference
  2516. // to the "bufferSize" param as usual to set up processing buffers.
  2517. *bufferSize = stream_.bufferSize;
  2518. } else {
  2519. if ( *bufferSize == 0 ) *bufferSize = preferSize;
  2520. else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2521. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2522. else if ( granularity == -1 ) {
  2523. // Make sure bufferSize is a power of two.
  2524. int log2_of_min_size = 0;
  2525. int log2_of_max_size = 0;
  2526. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2527. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2528. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2529. }
  2530. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2531. int min_delta_num = log2_of_min_size;
  2532. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2533. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2534. if (current_delta < min_delta) {
  2535. min_delta = current_delta;
  2536. min_delta_num = i;
  2537. }
  2538. }
  2539. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2540. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2541. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2542. }
  2543. else if ( granularity != 0 ) {
  2544. // Set to an even multiple of granularity, rounding up.
  2545. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2546. }
  2547. }
  2548. /*
  2549. // we don't use it anymore, see above!
  2550. // Just left it here for the case...
  2551. if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
  2552. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2553. goto error;
  2554. }
  2555. */
  2556. stream_.bufferSize = *bufferSize;
  2557. stream_.nBuffers = 2;
  2558. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2559. else stream_.userInterleaved = true;
  2560. // ASIO always uses non-interleaved buffers.
  2561. stream_.deviceInterleaved[mode] = false;
  2562. // Allocate, if necessary, our AsioHandle structure for the stream.
  2563. if ( handle == 0 ) {
  2564. try {
  2565. handle = new AsioHandle;
  2566. }
  2567. catch ( std::bad_alloc& ) {
  2568. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2569. goto error;
  2570. }
  2571. handle->bufferInfos = 0;
  2572. // Create a manual-reset event.
  2573. handle->condition = CreateEvent( NULL, // no security
  2574. TRUE, // manual-reset
  2575. FALSE, // non-signaled initially
  2576. NULL ); // unnamed
  2577. stream_.apiHandle = (void *) handle;
  2578. }
  2579. // Create the ASIO internal buffers. Since RtAudio sets up input
  2580. // and output separately, we'll have to dispose of previously
  2581. // created output buffers for a duplex stream.
  2582. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2583. ASIODisposeBuffers();
  2584. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2585. }
  2586. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2587. unsigned int i;
  2588. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2589. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2590. if ( handle->bufferInfos == NULL ) {
  2591. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2592. errorText_ = errorStream_.str();
  2593. goto error;
  2594. }
  2595. ASIOBufferInfo *infos;
  2596. infos = handle->bufferInfos;
  2597. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2598. infos->isInput = ASIOFalse;
  2599. infos->channelNum = i + stream_.channelOffset[0];
  2600. infos->buffers[0] = infos->buffers[1] = 0;
  2601. }
  2602. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2603. infos->isInput = ASIOTrue;
  2604. infos->channelNum = i + stream_.channelOffset[1];
  2605. infos->buffers[0] = infos->buffers[1] = 0;
  2606. }
  2607. // prepare for callbacks
  2608. stream_.sampleRate = sampleRate;
  2609. stream_.device[mode] = device;
  2610. stream_.mode = isDuplexInput ? DUPLEX : mode;
  2611. // store this class instance before registering callbacks, that are going to use it
  2612. asioCallbackInfo = &stream_.callbackInfo;
  2613. stream_.callbackInfo.object = (void *) this;
  2614. // Set up the ASIO callback structure and create the ASIO data buffers.
  2615. asioCallbacks.bufferSwitch = &bufferSwitch;
  2616. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2617. asioCallbacks.asioMessage = &asioMessages;
  2618. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2619. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2620. if ( result != ASE_OK ) {
  2621. // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
  2622. // but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver
  2623. // in that case, let's be naïve and try that instead
  2624. *bufferSize = preferSize;
  2625. stream_.bufferSize = *bufferSize;
  2626. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2627. }
  2628. if ( result != ASE_OK ) {
  2629. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2630. errorText_ = errorStream_.str();
  2631. goto error;
  2632. }
  2633. buffersAllocated = true;
  2634. stream_.state = STREAM_STOPPED;
  2635. // Set flags for buffer conversion.
  2636. stream_.doConvertBuffer[mode] = false;
  2637. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2638. stream_.doConvertBuffer[mode] = true;
  2639. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2640. stream_.nUserChannels[mode] > 1 )
  2641. stream_.doConvertBuffer[mode] = true;
  2642. // Allocate necessary internal buffers
  2643. unsigned long bufferBytes;
  2644. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2645. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2646. if ( stream_.userBuffer[mode] == NULL ) {
  2647. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2648. goto error;
  2649. }
  2650. if ( stream_.doConvertBuffer[mode] ) {
  2651. bool makeBuffer = true;
  2652. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2653. if ( isDuplexInput && stream_.deviceBuffer ) {
  2654. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2655. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2656. }
  2657. if ( makeBuffer ) {
  2658. bufferBytes *= *bufferSize;
  2659. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2660. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2661. if ( stream_.deviceBuffer == NULL ) {
  2662. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2663. goto error;
  2664. }
  2665. }
  2666. }
  2667. // Determine device latencies
  2668. long inputLatency, outputLatency;
  2669. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2670. if ( result != ASE_OK ) {
  2671. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2672. errorText_ = errorStream_.str();
  2673. error( RtAudioError::WARNING); // warn but don't fail
  2674. }
  2675. else {
  2676. stream_.latency[0] = outputLatency;
  2677. stream_.latency[1] = inputLatency;
  2678. }
  2679. // Setup the buffer conversion information structure. We don't use
  2680. // buffers to do channel offsets, so we override that parameter
  2681. // here.
  2682. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2683. return SUCCESS;
  2684. error:
  2685. if ( !isDuplexInput ) {
  2686. // the cleanup for error in the duplex input, is done by RtApi::openStream
  2687. // So we clean up for single channel only
  2688. if ( buffersAllocated )
  2689. ASIODisposeBuffers();
  2690. drivers.removeCurrentDriver();
  2691. if ( handle ) {
  2692. CloseHandle( handle->condition );
  2693. if ( handle->bufferInfos )
  2694. free( handle->bufferInfos );
  2695. delete handle;
  2696. stream_.apiHandle = 0;
  2697. }
  2698. if ( stream_.userBuffer[mode] ) {
  2699. free( stream_.userBuffer[mode] );
  2700. stream_.userBuffer[mode] = 0;
  2701. }
  2702. if ( stream_.deviceBuffer ) {
  2703. free( stream_.deviceBuffer );
  2704. stream_.deviceBuffer = 0;
  2705. }
  2706. }
  2707. return FAILURE;
  2708. }////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2709. void RtApiAsio :: closeStream()
  2710. {
  2711. if ( stream_.state == STREAM_CLOSED ) {
  2712. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2713. error( RtAudioError::WARNING );
  2714. return;
  2715. }
  2716. if ( stream_.state == STREAM_RUNNING ) {
  2717. stream_.state = STREAM_STOPPED;
  2718. ASIOStop();
  2719. }
  2720. ASIODisposeBuffers();
  2721. drivers.removeCurrentDriver();
  2722. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2723. if ( handle ) {
  2724. CloseHandle( handle->condition );
  2725. if ( handle->bufferInfos )
  2726. free( handle->bufferInfos );
  2727. delete handle;
  2728. stream_.apiHandle = 0;
  2729. }
  2730. for ( int i=0; i<2; i++ ) {
  2731. if ( stream_.userBuffer[i] ) {
  2732. free( stream_.userBuffer[i] );
  2733. stream_.userBuffer[i] = 0;
  2734. }
  2735. }
  2736. if ( stream_.deviceBuffer ) {
  2737. free( stream_.deviceBuffer );
  2738. stream_.deviceBuffer = 0;
  2739. }
  2740. stream_.mode = UNINITIALIZED;
  2741. stream_.state = STREAM_CLOSED;
  2742. }
  2743. bool stopThreadCalled = false;
  2744. void RtApiAsio :: startStream()
  2745. {
  2746. verifyStream();
  2747. if ( stream_.state == STREAM_RUNNING ) {
  2748. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2749. error( RtAudioError::WARNING );
  2750. return;
  2751. }
  2752. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2753. ASIOError result = ASIOStart();
  2754. if ( result != ASE_OK ) {
  2755. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2756. errorText_ = errorStream_.str();
  2757. goto unlock;
  2758. }
  2759. handle->drainCounter = 0;
  2760. handle->internalDrain = false;
  2761. ResetEvent( handle->condition );
  2762. stream_.state = STREAM_RUNNING;
  2763. asioXRun = false;
  2764. unlock:
  2765. stopThreadCalled = false;
  2766. if ( result == ASE_OK ) return;
  2767. error( RtAudioError::SYSTEM_ERROR );
  2768. }
  2769. void RtApiAsio :: stopStream()
  2770. {
  2771. verifyStream();
  2772. if ( stream_.state == STREAM_STOPPED ) {
  2773. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2774. error( RtAudioError::WARNING );
  2775. return;
  2776. }
  2777. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2778. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2779. if ( handle->drainCounter == 0 ) {
  2780. handle->drainCounter = 2;
  2781. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2782. }
  2783. }
  2784. stream_.state = STREAM_STOPPED;
  2785. ASIOError result = ASIOStop();
  2786. if ( result != ASE_OK ) {
  2787. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2788. errorText_ = errorStream_.str();
  2789. }
  2790. if ( result == ASE_OK ) return;
  2791. error( RtAudioError::SYSTEM_ERROR );
  2792. }
  2793. void RtApiAsio :: abortStream()
  2794. {
  2795. verifyStream();
  2796. if ( stream_.state == STREAM_STOPPED ) {
  2797. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2798. error( RtAudioError::WARNING );
  2799. return;
  2800. }
  2801. // The following lines were commented-out because some behavior was
  2802. // noted where the device buffers need to be zeroed to avoid
  2803. // continuing sound, even when the device buffers are completely
  2804. // disposed. So now, calling abort is the same as calling stop.
  2805. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2806. // handle->drainCounter = 2;
  2807. stopStream();
  2808. }
  2809. // This function will be called by a spawned thread when the user
  2810. // callback function signals that the stream should be stopped or
  2811. // aborted. It is necessary to handle it this way because the
  2812. // callbackEvent() function must return before the ASIOStop()
  2813. // function will return.
  2814. static unsigned __stdcall asioStopStream( void *ptr )
  2815. {
  2816. CallbackInfo *info = (CallbackInfo *) ptr;
  2817. RtApiAsio *object = (RtApiAsio *) info->object;
  2818. object->stopStream();
  2819. _endthreadex( 0 );
  2820. return 0;
  2821. }
  2822. bool RtApiAsio :: callbackEvent( long bufferIndex )
  2823. {
  2824. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2825. if ( stream_.state == STREAM_CLOSED ) {
  2826. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2827. error( RtAudioError::WARNING );
  2828. return FAILURE;
  2829. }
  2830. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2831. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2832. // Check if we were draining the stream and signal if finished.
  2833. if ( handle->drainCounter > 3 ) {
  2834. stream_.state = STREAM_STOPPING;
  2835. if ( handle->internalDrain == false )
  2836. SetEvent( handle->condition );
  2837. else { // spawn a thread to stop the stream
  2838. unsigned threadId;
  2839. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2840. &stream_.callbackInfo, 0, &threadId );
  2841. }
  2842. return SUCCESS;
  2843. }
  2844. // Invoke user callback to get fresh output data UNLESS we are
  2845. // draining stream.
  2846. if ( handle->drainCounter == 0 ) {
  2847. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2848. double streamTime = getStreamTime();
  2849. RtAudioStreamStatus status = 0;
  2850. if ( stream_.mode != INPUT && asioXRun == true ) {
  2851. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2852. asioXRun = false;
  2853. }
  2854. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  2855. status |= RTAUDIO_INPUT_OVERFLOW;
  2856. asioXRun = false;
  2857. }
  2858. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2859. stream_.bufferSize, streamTime, status, info->userData );
  2860. if ( cbReturnValue == 2 ) {
  2861. stream_.state = STREAM_STOPPING;
  2862. handle->drainCounter = 2;
  2863. unsigned threadId;
  2864. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2865. &stream_.callbackInfo, 0, &threadId );
  2866. return SUCCESS;
  2867. }
  2868. else if ( cbReturnValue == 1 ) {
  2869. handle->drainCounter = 1;
  2870. handle->internalDrain = true;
  2871. }
  2872. }
  2873. unsigned int nChannels, bufferBytes, i, j;
  2874. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2875. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2876. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  2877. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2878. for ( i=0, j=0; i<nChannels; i++ ) {
  2879. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2880. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  2881. }
  2882. }
  2883. else if ( stream_.doConvertBuffer[0] ) {
  2884. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2885. if ( stream_.doByteSwap[0] )
  2886. byteSwapBuffer( stream_.deviceBuffer,
  2887. stream_.bufferSize * stream_.nDeviceChannels[0],
  2888. stream_.deviceFormat[0] );
  2889. for ( i=0, j=0; i<nChannels; i++ ) {
  2890. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2891. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2892. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  2893. }
  2894. }
  2895. else {
  2896. if ( stream_.doByteSwap[0] )
  2897. byteSwapBuffer( stream_.userBuffer[0],
  2898. stream_.bufferSize * stream_.nUserChannels[0],
  2899. stream_.userFormat );
  2900. for ( i=0, j=0; i<nChannels; i++ ) {
  2901. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2902. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2903. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  2904. }
  2905. }
  2906. }
  2907. // Don't bother draining input
  2908. if ( handle->drainCounter ) {
  2909. handle->drainCounter++;
  2910. goto unlock;
  2911. }
  2912. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2913. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  2914. if (stream_.doConvertBuffer[1]) {
  2915. // Always interleave ASIO input data.
  2916. for ( i=0, j=0; i<nChannels; i++ ) {
  2917. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  2918. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  2919. handle->bufferInfos[i].buffers[bufferIndex],
  2920. bufferBytes );
  2921. }
  2922. if ( stream_.doByteSwap[1] )
  2923. byteSwapBuffer( stream_.deviceBuffer,
  2924. stream_.bufferSize * stream_.nDeviceChannels[1],
  2925. stream_.deviceFormat[1] );
  2926. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2927. }
  2928. else {
  2929. for ( i=0, j=0; i<nChannels; i++ ) {
  2930. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  2931. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  2932. handle->bufferInfos[i].buffers[bufferIndex],
  2933. bufferBytes );
  2934. }
  2935. }
  2936. if ( stream_.doByteSwap[1] )
  2937. byteSwapBuffer( stream_.userBuffer[1],
  2938. stream_.bufferSize * stream_.nUserChannels[1],
  2939. stream_.userFormat );
  2940. }
  2941. }
  2942. unlock:
  2943. // The following call was suggested by Malte Clasen. While the API
  2944. // documentation indicates it should not be required, some device
  2945. // drivers apparently do not function correctly without it.
  2946. ASIOOutputReady();
  2947. RtApi::tickStreamTime();
  2948. return SUCCESS;
  2949. }
  2950. static void sampleRateChanged( ASIOSampleRate sRate )
  2951. {
  2952. // The ASIO documentation says that this usually only happens during
  2953. // external sync. Audio processing is not stopped by the driver,
  2954. // actual sample rate might not have even changed, maybe only the
  2955. // sample rate status of an AES/EBU or S/PDIF digital input at the
  2956. // audio device.
  2957. RtApi *object = (RtApi *) asioCallbackInfo->object;
  2958. try {
  2959. object->stopStream();
  2960. }
  2961. catch ( RtAudioError &exception ) {
  2962. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  2963. return;
  2964. }
  2965. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  2966. }
  2967. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  2968. {
  2969. long ret = 0;
  2970. switch( selector ) {
  2971. case kAsioSelectorSupported:
  2972. if ( value == kAsioResetRequest
  2973. || value == kAsioEngineVersion
  2974. || value == kAsioResyncRequest
  2975. || value == kAsioLatenciesChanged
  2976. // The following three were added for ASIO 2.0, you don't
  2977. // necessarily have to support them.
  2978. || value == kAsioSupportsTimeInfo
  2979. || value == kAsioSupportsTimeCode
  2980. || value == kAsioSupportsInputMonitor)
  2981. ret = 1L;
  2982. break;
  2983. case kAsioResetRequest:
  2984. // Defer the task and perform the reset of the driver during the
  2985. // next "safe" situation. You cannot reset the driver right now,
  2986. // as this code is called from the driver. Reset the driver is
  2987. // done by completely destruct is. I.e. ASIOStop(),
  2988. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  2989. // driver again.
  2990. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  2991. ret = 1L;
  2992. break;
  2993. case kAsioResyncRequest:
  2994. // This informs the application that the driver encountered some
  2995. // non-fatal data loss. It is used for synchronization purposes
  2996. // of different media. Added mainly to work around the Win16Mutex
  2997. // problems in Windows 95/98 with the Windows Multimedia system,
  2998. // which could lose data because the Mutex was held too long by
  2999. // another thread. However a driver can issue it in other
  3000. // situations, too.
  3001. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3002. asioXRun = true;
  3003. ret = 1L;
  3004. break;
  3005. case kAsioLatenciesChanged:
  3006. // This will inform the host application that the drivers were
  3007. // latencies changed. Beware, it this does not mean that the
  3008. // buffer sizes have changed! You might need to update internal
  3009. // delay data.
  3010. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3011. ret = 1L;
  3012. break;
  3013. case kAsioEngineVersion:
  3014. // Return the supported ASIO version of the host application. If
  3015. // a host application does not implement this selector, ASIO 1.0
  3016. // is assumed by the driver.
  3017. ret = 2L;
  3018. break;
  3019. case kAsioSupportsTimeInfo:
  3020. // Informs the driver whether the
  3021. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3022. // For compatibility with ASIO 1.0 drivers the host application
  3023. // should always support the "old" bufferSwitch method, too.
  3024. ret = 0;
  3025. break;
  3026. case kAsioSupportsTimeCode:
  3027. // Informs the driver whether application is interested in time
  3028. // code info. If an application does not need to know about time
  3029. // code, the driver has less work to do.
  3030. ret = 0;
  3031. break;
  3032. }
  3033. return ret;
  3034. }
  3035. static const char* getAsioErrorString( ASIOError result )
  3036. {
  3037. struct Messages
  3038. {
  3039. ASIOError value;
  3040. const char*message;
  3041. };
  3042. static const Messages m[] =
  3043. {
  3044. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3045. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3046. { ASE_InvalidParameter, "Invalid input parameter." },
  3047. { ASE_InvalidMode, "Invalid mode." },
  3048. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3049. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3050. { ASE_NoMemory, "Not enough memory to complete the request." }
  3051. };
  3052. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3053. if ( m[i].value == result ) return m[i].message;
  3054. return "Unknown error.";
  3055. }
  3056. //******************** End of __WINDOWS_ASIO__ *********************//
  3057. #endif
  3058. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3059. // Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
  3060. // - Introduces support for the Windows WASAPI API
  3061. // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
  3062. // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
  3063. // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
  3064. #ifndef INITGUID
  3065. #define INITGUID
  3066. #endif
  3067. #include <audioclient.h>
  3068. #include <avrt.h>
  3069. #include <mmdeviceapi.h>
  3070. #include <functiondiscoverykeys_devpkey.h>
  3071. #include <sstream>
  3072. //=============================================================================
  3073. #define SAFE_RELEASE( objectPtr )\
  3074. if ( objectPtr )\
  3075. {\
  3076. objectPtr->Release();\
  3077. objectPtr = NULL;\
  3078. }
  3079. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3080. //-----------------------------------------------------------------------------
  3081. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3082. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3083. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3084. // provide intermediate storage for read / write synchronization.
  3085. class WasapiBuffer
  3086. {
  3087. public:
  3088. WasapiBuffer()
  3089. : buffer_( NULL ),
  3090. bufferSize_( 0 ),
  3091. inIndex_( 0 ),
  3092. outIndex_( 0 ) {}
  3093. ~WasapiBuffer() {
  3094. free( buffer_ );
  3095. }
  3096. // sets the length of the internal ring buffer
  3097. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3098. free( buffer_ );
  3099. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3100. bufferSize_ = bufferSize;
  3101. inIndex_ = 0;
  3102. outIndex_ = 0;
  3103. }
  3104. // attempt to push a buffer into the ring buffer at the current "in" index
  3105. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3106. {
  3107. if ( !buffer || // incoming buffer is NULL
  3108. bufferSize == 0 || // incoming buffer has no data
  3109. bufferSize > bufferSize_ ) // incoming buffer too large
  3110. {
  3111. return false;
  3112. }
  3113. unsigned int relOutIndex = outIndex_;
  3114. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3115. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3116. relOutIndex += bufferSize_;
  3117. }
  3118. // "in" index can end on the "out" index but cannot begin at it
  3119. if ( inIndex_ <= relOutIndex && inIndexEnd > relOutIndex ) {
  3120. return false; // not enough space between "in" index and "out" index
  3121. }
  3122. // copy buffer from external to internal
  3123. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3124. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3125. int fromInSize = bufferSize - fromZeroSize;
  3126. switch( format )
  3127. {
  3128. case RTAUDIO_SINT8:
  3129. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3130. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3131. break;
  3132. case RTAUDIO_SINT16:
  3133. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3134. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3135. break;
  3136. case RTAUDIO_SINT24:
  3137. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3138. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3139. break;
  3140. case RTAUDIO_SINT32:
  3141. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3142. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3143. break;
  3144. case RTAUDIO_FLOAT32:
  3145. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3146. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3147. break;
  3148. case RTAUDIO_FLOAT64:
  3149. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3150. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3151. break;
  3152. }
  3153. // update "in" index
  3154. inIndex_ += bufferSize;
  3155. inIndex_ %= bufferSize_;
  3156. return true;
  3157. }
  3158. // attempt to pull a buffer from the ring buffer from the current "out" index
  3159. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3160. {
  3161. if ( !buffer || // incoming buffer is NULL
  3162. bufferSize == 0 || // incoming buffer has no data
  3163. bufferSize > bufferSize_ ) // incoming buffer too large
  3164. {
  3165. return false;
  3166. }
  3167. unsigned int relInIndex = inIndex_;
  3168. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3169. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3170. relInIndex += bufferSize_;
  3171. }
  3172. // "out" index can begin at and end on the "in" index
  3173. if ( outIndex_ < relInIndex && outIndexEnd > relInIndex ) {
  3174. return false; // not enough space between "out" index and "in" index
  3175. }
  3176. // copy buffer from internal to external
  3177. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3178. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3179. int fromOutSize = bufferSize - fromZeroSize;
  3180. switch( format )
  3181. {
  3182. case RTAUDIO_SINT8:
  3183. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3184. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3185. break;
  3186. case RTAUDIO_SINT16:
  3187. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3188. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3189. break;
  3190. case RTAUDIO_SINT24:
  3191. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3192. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3193. break;
  3194. case RTAUDIO_SINT32:
  3195. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3196. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3197. break;
  3198. case RTAUDIO_FLOAT32:
  3199. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3200. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3201. break;
  3202. case RTAUDIO_FLOAT64:
  3203. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3204. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3205. break;
  3206. }
  3207. // update "out" index
  3208. outIndex_ += bufferSize;
  3209. outIndex_ %= bufferSize_;
  3210. return true;
  3211. }
  3212. private:
  3213. char* buffer_;
  3214. unsigned int bufferSize_;
  3215. unsigned int inIndex_;
  3216. unsigned int outIndex_;
  3217. };
  3218. //-----------------------------------------------------------------------------
  3219. // A structure to hold various information related to the WASAPI implementation.
  3220. struct WasapiHandle
  3221. {
  3222. IAudioClient* captureAudioClient;
  3223. IAudioClient* renderAudioClient;
  3224. IAudioCaptureClient* captureClient;
  3225. IAudioRenderClient* renderClient;
  3226. HANDLE captureEvent;
  3227. HANDLE renderEvent;
  3228. WasapiHandle()
  3229. : captureAudioClient( NULL ),
  3230. renderAudioClient( NULL ),
  3231. captureClient( NULL ),
  3232. renderClient( NULL ),
  3233. captureEvent( NULL ),
  3234. renderEvent( NULL ) {}
  3235. };
  3236. //=============================================================================
  3237. RtApiWasapi::RtApiWasapi()
  3238. : coInitialized_( false ), deviceEnumerator_( NULL )
  3239. {
  3240. // WASAPI can run either apartment or multi-threaded
  3241. HRESULT hr = CoInitialize( NULL );
  3242. if ( !FAILED( hr ) )
  3243. coInitialized_ = true;
  3244. // Instantiate device enumerator
  3245. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3246. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3247. ( void** ) &deviceEnumerator_ );
  3248. if ( FAILED( hr ) ) {
  3249. errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";
  3250. error( RtAudioError::DRIVER_ERROR );
  3251. }
  3252. }
  3253. //-----------------------------------------------------------------------------
  3254. RtApiWasapi::~RtApiWasapi()
  3255. {
  3256. if ( stream_.state != STREAM_CLOSED )
  3257. closeStream();
  3258. SAFE_RELEASE( deviceEnumerator_ );
  3259. // If this object previously called CoInitialize()
  3260. if ( coInitialized_ )
  3261. CoUninitialize();
  3262. }
  3263. //=============================================================================
  3264. unsigned int RtApiWasapi::getDeviceCount( void )
  3265. {
  3266. unsigned int captureDeviceCount = 0;
  3267. unsigned int renderDeviceCount = 0;
  3268. IMMDeviceCollection* captureDevices = NULL;
  3269. IMMDeviceCollection* renderDevices = NULL;
  3270. // Count capture devices
  3271. errorText_.clear();
  3272. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3273. if ( FAILED( hr ) ) {
  3274. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3275. goto Exit;
  3276. }
  3277. hr = captureDevices->GetCount( &captureDeviceCount );
  3278. if ( FAILED( hr ) ) {
  3279. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3280. goto Exit;
  3281. }
  3282. // Count render devices
  3283. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3284. if ( FAILED( hr ) ) {
  3285. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3286. goto Exit;
  3287. }
  3288. hr = renderDevices->GetCount( &renderDeviceCount );
  3289. if ( FAILED( hr ) ) {
  3290. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3291. goto Exit;
  3292. }
  3293. Exit:
  3294. // release all references
  3295. SAFE_RELEASE( captureDevices );
  3296. SAFE_RELEASE( renderDevices );
  3297. if ( errorText_.empty() )
  3298. return captureDeviceCount + renderDeviceCount;
  3299. error( RtAudioError::DRIVER_ERROR );
  3300. return 0;
  3301. }
  3302. //-----------------------------------------------------------------------------
  3303. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3304. {
  3305. RtAudio::DeviceInfo info;
  3306. unsigned int captureDeviceCount = 0;
  3307. unsigned int renderDeviceCount = 0;
  3308. std::string defaultDeviceName;
  3309. bool isCaptureDevice = false;
  3310. PROPVARIANT deviceNameProp;
  3311. PROPVARIANT defaultDeviceNameProp;
  3312. IMMDeviceCollection* captureDevices = NULL;
  3313. IMMDeviceCollection* renderDevices = NULL;
  3314. IMMDevice* devicePtr = NULL;
  3315. IMMDevice* defaultDevicePtr = NULL;
  3316. IAudioClient* audioClient = NULL;
  3317. IPropertyStore* devicePropStore = NULL;
  3318. IPropertyStore* defaultDevicePropStore = NULL;
  3319. WAVEFORMATEX* deviceFormat = NULL;
  3320. WAVEFORMATEX* closestMatchFormat = NULL;
  3321. // probed
  3322. info.probed = false;
  3323. // Count capture devices
  3324. errorText_.clear();
  3325. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3326. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3327. if ( FAILED( hr ) ) {
  3328. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3329. goto Exit;
  3330. }
  3331. hr = captureDevices->GetCount( &captureDeviceCount );
  3332. if ( FAILED( hr ) ) {
  3333. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3334. goto Exit;
  3335. }
  3336. // Count render devices
  3337. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3338. if ( FAILED( hr ) ) {
  3339. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3340. goto Exit;
  3341. }
  3342. hr = renderDevices->GetCount( &renderDeviceCount );
  3343. if ( FAILED( hr ) ) {
  3344. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3345. goto Exit;
  3346. }
  3347. // validate device index
  3348. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3349. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3350. errorType = RtAudioError::INVALID_USE;
  3351. goto Exit;
  3352. }
  3353. // determine whether index falls within capture or render devices
  3354. if ( device >= renderDeviceCount ) {
  3355. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3356. if ( FAILED( hr ) ) {
  3357. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3358. goto Exit;
  3359. }
  3360. isCaptureDevice = true;
  3361. }
  3362. else {
  3363. hr = renderDevices->Item( device, &devicePtr );
  3364. if ( FAILED( hr ) ) {
  3365. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3366. goto Exit;
  3367. }
  3368. isCaptureDevice = false;
  3369. }
  3370. // get default device name
  3371. if ( isCaptureDevice ) {
  3372. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3373. if ( FAILED( hr ) ) {
  3374. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3375. goto Exit;
  3376. }
  3377. }
  3378. else {
  3379. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3380. if ( FAILED( hr ) ) {
  3381. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3382. goto Exit;
  3383. }
  3384. }
  3385. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3386. if ( FAILED( hr ) ) {
  3387. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3388. goto Exit;
  3389. }
  3390. PropVariantInit( &defaultDeviceNameProp );
  3391. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3392. if ( FAILED( hr ) ) {
  3393. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3394. goto Exit;
  3395. }
  3396. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3397. // name
  3398. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3399. if ( FAILED( hr ) ) {
  3400. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3401. goto Exit;
  3402. }
  3403. PropVariantInit( &deviceNameProp );
  3404. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3405. if ( FAILED( hr ) ) {
  3406. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3407. goto Exit;
  3408. }
  3409. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3410. // is default
  3411. if ( isCaptureDevice ) {
  3412. info.isDefaultInput = info.name == defaultDeviceName;
  3413. info.isDefaultOutput = false;
  3414. }
  3415. else {
  3416. info.isDefaultInput = false;
  3417. info.isDefaultOutput = info.name == defaultDeviceName;
  3418. }
  3419. // channel count
  3420. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3421. if ( FAILED( hr ) ) {
  3422. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3423. goto Exit;
  3424. }
  3425. hr = audioClient->GetMixFormat( &deviceFormat );
  3426. if ( FAILED( hr ) ) {
  3427. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3428. goto Exit;
  3429. }
  3430. if ( isCaptureDevice ) {
  3431. info.inputChannels = deviceFormat->nChannels;
  3432. info.outputChannels = 0;
  3433. info.duplexChannels = 0;
  3434. }
  3435. else {
  3436. info.inputChannels = 0;
  3437. info.outputChannels = deviceFormat->nChannels;
  3438. info.duplexChannels = 0;
  3439. }
  3440. // sample rates (WASAPI only supports the one native sample rate)
  3441. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3442. info.sampleRates.clear();
  3443. info.sampleRates.push_back( deviceFormat->nSamplesPerSec );
  3444. // native format
  3445. info.nativeFormats = 0;
  3446. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3447. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3448. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3449. {
  3450. if ( deviceFormat->wBitsPerSample == 32 ) {
  3451. info.nativeFormats |= RTAUDIO_FLOAT32;
  3452. }
  3453. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3454. info.nativeFormats |= RTAUDIO_FLOAT64;
  3455. }
  3456. }
  3457. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3458. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3459. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3460. {
  3461. if ( deviceFormat->wBitsPerSample == 8 ) {
  3462. info.nativeFormats |= RTAUDIO_SINT8;
  3463. }
  3464. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3465. info.nativeFormats |= RTAUDIO_SINT16;
  3466. }
  3467. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3468. info.nativeFormats |= RTAUDIO_SINT24;
  3469. }
  3470. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3471. info.nativeFormats |= RTAUDIO_SINT32;
  3472. }
  3473. }
  3474. // probed
  3475. info.probed = true;
  3476. Exit:
  3477. // release all references
  3478. PropVariantClear( &deviceNameProp );
  3479. PropVariantClear( &defaultDeviceNameProp );
  3480. SAFE_RELEASE( captureDevices );
  3481. SAFE_RELEASE( renderDevices );
  3482. SAFE_RELEASE( devicePtr );
  3483. SAFE_RELEASE( defaultDevicePtr );
  3484. SAFE_RELEASE( audioClient );
  3485. SAFE_RELEASE( devicePropStore );
  3486. SAFE_RELEASE( defaultDevicePropStore );
  3487. CoTaskMemFree( deviceFormat );
  3488. CoTaskMemFree( closestMatchFormat );
  3489. if ( !errorText_.empty() )
  3490. error( errorType );
  3491. return info;
  3492. }
  3493. //-----------------------------------------------------------------------------
  3494. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3495. {
  3496. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3497. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3498. return i;
  3499. }
  3500. }
  3501. return 0;
  3502. }
  3503. //-----------------------------------------------------------------------------
  3504. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3505. {
  3506. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3507. if ( getDeviceInfo( i ).isDefaultInput ) {
  3508. return i;
  3509. }
  3510. }
  3511. return 0;
  3512. }
  3513. //-----------------------------------------------------------------------------
  3514. void RtApiWasapi::closeStream( void )
  3515. {
  3516. if ( stream_.state == STREAM_CLOSED ) {
  3517. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3518. error( RtAudioError::WARNING );
  3519. return;
  3520. }
  3521. if ( stream_.state != STREAM_STOPPED )
  3522. stopStream();
  3523. // clean up stream memory
  3524. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3525. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3526. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3527. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3528. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3529. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3530. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3531. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3532. delete ( WasapiHandle* ) stream_.apiHandle;
  3533. stream_.apiHandle = NULL;
  3534. for ( int i = 0; i < 2; i++ ) {
  3535. if ( stream_.userBuffer[i] ) {
  3536. free( stream_.userBuffer[i] );
  3537. stream_.userBuffer[i] = 0;
  3538. }
  3539. }
  3540. if ( stream_.deviceBuffer ) {
  3541. free( stream_.deviceBuffer );
  3542. stream_.deviceBuffer = 0;
  3543. }
  3544. // update stream state
  3545. stream_.state = STREAM_CLOSED;
  3546. }
  3547. //-----------------------------------------------------------------------------
  3548. void RtApiWasapi::startStream( void )
  3549. {
  3550. verifyStream();
  3551. if ( stream_.state == STREAM_RUNNING ) {
  3552. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3553. error( RtAudioError::WARNING );
  3554. return;
  3555. }
  3556. // update stream state
  3557. stream_.state = STREAM_RUNNING;
  3558. // create WASAPI stream thread
  3559. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3560. if ( !stream_.callbackInfo.thread ) {
  3561. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3562. error( RtAudioError::THREAD_ERROR );
  3563. }
  3564. else {
  3565. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3566. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3567. }
  3568. }
  3569. //-----------------------------------------------------------------------------
  3570. void RtApiWasapi::stopStream( void )
  3571. {
  3572. verifyStream();
  3573. if ( stream_.state == STREAM_STOPPED ) {
  3574. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3575. error( RtAudioError::WARNING );
  3576. return;
  3577. }
  3578. // inform stream thread by setting stream state to STREAM_STOPPING
  3579. stream_.state = STREAM_STOPPING;
  3580. // wait until stream thread is stopped
  3581. while( stream_.state != STREAM_STOPPED ) {
  3582. Sleep( 1 );
  3583. }
  3584. // Wait for the last buffer to play before stopping.
  3585. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3586. // stop capture client if applicable
  3587. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3588. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3589. if ( FAILED( hr ) ) {
  3590. errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";
  3591. error( RtAudioError::DRIVER_ERROR );
  3592. return;
  3593. }
  3594. }
  3595. // stop render client if applicable
  3596. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3597. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3598. if ( FAILED( hr ) ) {
  3599. errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";
  3600. error( RtAudioError::DRIVER_ERROR );
  3601. return;
  3602. }
  3603. }
  3604. // close thread handle
  3605. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3606. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3607. error( RtAudioError::THREAD_ERROR );
  3608. return;
  3609. }
  3610. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3611. }
  3612. //-----------------------------------------------------------------------------
  3613. void RtApiWasapi::abortStream( void )
  3614. {
  3615. verifyStream();
  3616. if ( stream_.state == STREAM_STOPPED ) {
  3617. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3618. error( RtAudioError::WARNING );
  3619. return;
  3620. }
  3621. // inform stream thread by setting stream state to STREAM_STOPPING
  3622. stream_.state = STREAM_STOPPING;
  3623. // wait until stream thread is stopped
  3624. while ( stream_.state != STREAM_STOPPED ) {
  3625. Sleep( 1 );
  3626. }
  3627. // stop capture client if applicable
  3628. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3629. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3630. if ( FAILED( hr ) ) {
  3631. errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";
  3632. error( RtAudioError::DRIVER_ERROR );
  3633. return;
  3634. }
  3635. }
  3636. // stop render client if applicable
  3637. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3638. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3639. if ( FAILED( hr ) ) {
  3640. errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";
  3641. error( RtAudioError::DRIVER_ERROR );
  3642. return;
  3643. }
  3644. }
  3645. // close thread handle
  3646. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3647. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3648. error( RtAudioError::THREAD_ERROR );
  3649. return;
  3650. }
  3651. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3652. }
  3653. //-----------------------------------------------------------------------------
  3654. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3655. unsigned int firstChannel, unsigned int sampleRate,
  3656. RtAudioFormat format, unsigned int* bufferSize,
  3657. RtAudio::StreamOptions* options )
  3658. {
  3659. bool methodResult = FAILURE;
  3660. unsigned int captureDeviceCount = 0;
  3661. unsigned int renderDeviceCount = 0;
  3662. IMMDeviceCollection* captureDevices = NULL;
  3663. IMMDeviceCollection* renderDevices = NULL;
  3664. IMMDevice* devicePtr = NULL;
  3665. WAVEFORMATEX* deviceFormat = NULL;
  3666. unsigned int bufferBytes;
  3667. stream_.state = STREAM_STOPPED;
  3668. RtAudio::DeviceInfo deviceInfo;
  3669. // create API Handle if not already created
  3670. if ( !stream_.apiHandle )
  3671. stream_.apiHandle = ( void* ) new WasapiHandle();
  3672. // Count capture devices
  3673. errorText_.clear();
  3674. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3675. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3676. if ( FAILED( hr ) ) {
  3677. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  3678. goto Exit;
  3679. }
  3680. hr = captureDevices->GetCount( &captureDeviceCount );
  3681. if ( FAILED( hr ) ) {
  3682. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  3683. goto Exit;
  3684. }
  3685. // Count render devices
  3686. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3687. if ( FAILED( hr ) ) {
  3688. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  3689. goto Exit;
  3690. }
  3691. hr = renderDevices->GetCount( &renderDeviceCount );
  3692. if ( FAILED( hr ) ) {
  3693. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  3694. goto Exit;
  3695. }
  3696. // validate device index
  3697. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3698. errorType = RtAudioError::INVALID_USE;
  3699. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  3700. goto Exit;
  3701. }
  3702. deviceInfo = getDeviceInfo( device );
  3703. // validate sample rate
  3704. if ( sampleRate != deviceInfo.preferredSampleRate )
  3705. {
  3706. errorType = RtAudioError::INVALID_USE;
  3707. std::stringstream ss;
  3708. ss << "RtApiWasapi::probeDeviceOpen: " << sampleRate
  3709. << "Hz sample rate not supported. This device only supports "
  3710. << deviceInfo.preferredSampleRate << "Hz.";
  3711. errorText_ = ss.str();
  3712. goto Exit;
  3713. }
  3714. // determine whether index falls within capture or render devices
  3715. if ( device >= renderDeviceCount ) {
  3716. if ( mode != INPUT ) {
  3717. errorType = RtAudioError::INVALID_USE;
  3718. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  3719. goto Exit;
  3720. }
  3721. // retrieve captureAudioClient from devicePtr
  3722. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3723. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3724. if ( FAILED( hr ) ) {
  3725. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  3726. goto Exit;
  3727. }
  3728. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3729. NULL, ( void** ) &captureAudioClient );
  3730. if ( FAILED( hr ) ) {
  3731. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3732. goto Exit;
  3733. }
  3734. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  3735. if ( FAILED( hr ) ) {
  3736. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3737. goto Exit;
  3738. }
  3739. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3740. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3741. }
  3742. else {
  3743. if ( mode != OUTPUT ) {
  3744. errorType = RtAudioError::INVALID_USE;
  3745. errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";
  3746. goto Exit;
  3747. }
  3748. // retrieve renderAudioClient from devicePtr
  3749. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3750. hr = renderDevices->Item( device, &devicePtr );
  3751. if ( FAILED( hr ) ) {
  3752. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  3753. goto Exit;
  3754. }
  3755. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3756. NULL, ( void** ) &renderAudioClient );
  3757. if ( FAILED( hr ) ) {
  3758. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3759. goto Exit;
  3760. }
  3761. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  3762. if ( FAILED( hr ) ) {
  3763. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3764. goto Exit;
  3765. }
  3766. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3767. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3768. }
  3769. // fill stream data
  3770. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  3771. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  3772. stream_.mode = DUPLEX;
  3773. }
  3774. else {
  3775. stream_.mode = mode;
  3776. }
  3777. stream_.device[mode] = device;
  3778. stream_.doByteSwap[mode] = false;
  3779. stream_.sampleRate = sampleRate;
  3780. stream_.bufferSize = *bufferSize;
  3781. stream_.nBuffers = 1;
  3782. stream_.nUserChannels[mode] = channels;
  3783. stream_.channelOffset[mode] = firstChannel;
  3784. stream_.userFormat = format;
  3785. stream_.deviceFormat[mode] = deviceInfo.nativeFormats;
  3786. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  3787. stream_.userInterleaved = false;
  3788. else
  3789. stream_.userInterleaved = true;
  3790. stream_.deviceInterleaved[mode] = true;
  3791. // Set flags for buffer conversion.
  3792. stream_.doConvertBuffer[mode] = false;
  3793. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  3794. stream_.nUserChannels != stream_.nDeviceChannels )
  3795. stream_.doConvertBuffer[mode] = true;
  3796. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  3797. stream_.nUserChannels[mode] > 1 )
  3798. stream_.doConvertBuffer[mode] = true;
  3799. if ( stream_.doConvertBuffer[mode] )
  3800. setConvertInfo( mode, 0 );
  3801. // Allocate necessary internal buffers
  3802. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  3803. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  3804. if ( !stream_.userBuffer[mode] ) {
  3805. errorType = RtAudioError::MEMORY_ERROR;
  3806. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  3807. goto Exit;
  3808. }
  3809. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  3810. stream_.callbackInfo.priority = 15;
  3811. else
  3812. stream_.callbackInfo.priority = 0;
  3813. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  3814. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  3815. methodResult = SUCCESS;
  3816. Exit:
  3817. //clean up
  3818. SAFE_RELEASE( captureDevices );
  3819. SAFE_RELEASE( renderDevices );
  3820. SAFE_RELEASE( devicePtr );
  3821. CoTaskMemFree( deviceFormat );
  3822. // if method failed, close the stream
  3823. if ( methodResult == FAILURE )
  3824. closeStream();
  3825. if ( !errorText_.empty() )
  3826. error( errorType );
  3827. return methodResult;
  3828. }
  3829. //=============================================================================
  3830. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  3831. {
  3832. if ( wasapiPtr )
  3833. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  3834. return 0;
  3835. }
  3836. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  3837. {
  3838. if ( wasapiPtr )
  3839. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  3840. return 0;
  3841. }
  3842. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  3843. {
  3844. if ( wasapiPtr )
  3845. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  3846. return 0;
  3847. }
  3848. //-----------------------------------------------------------------------------
  3849. void RtApiWasapi::wasapiThread()
  3850. {
  3851. // as this is a new thread, we must CoInitialize it
  3852. CoInitialize( NULL );
  3853. HRESULT hr;
  3854. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3855. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3856. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  3857. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  3858. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  3859. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  3860. WAVEFORMATEX* captureFormat = NULL;
  3861. WAVEFORMATEX* renderFormat = NULL;
  3862. WasapiBuffer captureBuffer;
  3863. WasapiBuffer renderBuffer;
  3864. // declare local stream variables
  3865. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  3866. BYTE* streamBuffer = NULL;
  3867. unsigned long captureFlags = 0;
  3868. unsigned int bufferFrameCount = 0;
  3869. unsigned int numFramesPadding = 0;
  3870. bool callbackPushed = false;
  3871. bool callbackPulled = false;
  3872. bool callbackStopped = false;
  3873. int callbackResult = 0;
  3874. unsigned int deviceBuffSize = 0;
  3875. errorText_.clear();
  3876. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3877. // Attempt to assign "Pro Audio" characteristic to thread
  3878. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  3879. if ( AvrtDll ) {
  3880. DWORD taskIndex = 0;
  3881. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  3882. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  3883. FreeLibrary( AvrtDll );
  3884. }
  3885. // start capture stream if applicable
  3886. if ( captureAudioClient ) {
  3887. hr = captureAudioClient->GetMixFormat( &captureFormat );
  3888. if ( FAILED( hr ) ) {
  3889. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  3890. goto Exit;
  3891. }
  3892. // initialize capture stream according to desire buffer size
  3893. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) stream_.bufferSize * 10000000 / captureFormat->nSamplesPerSec );
  3894. if ( !captureClient ) {
  3895. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  3896. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  3897. desiredBufferPeriod,
  3898. desiredBufferPeriod,
  3899. captureFormat,
  3900. NULL );
  3901. if ( FAILED( hr ) ) {
  3902. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  3903. goto Exit;
  3904. }
  3905. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  3906. ( void** ) &captureClient );
  3907. if ( FAILED( hr ) ) {
  3908. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  3909. goto Exit;
  3910. }
  3911. // configure captureEvent to trigger on every available capture buffer
  3912. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  3913. if ( !captureEvent ) {
  3914. errorType = RtAudioError::SYSTEM_ERROR;
  3915. errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  3916. goto Exit;
  3917. }
  3918. hr = captureAudioClient->SetEventHandle( captureEvent );
  3919. if ( FAILED( hr ) ) {
  3920. errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  3921. goto Exit;
  3922. }
  3923. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  3924. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  3925. }
  3926. unsigned int inBufferSize = 0;
  3927. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  3928. if ( FAILED( hr ) ) {
  3929. errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  3930. goto Exit;
  3931. }
  3932. // scale outBufferSize according to stream->user sample rate ratio
  3933. unsigned int outBufferSize = ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[INPUT];
  3934. inBufferSize *= stream_.nDeviceChannels[INPUT];
  3935. // set captureBuffer size
  3936. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  3937. // reset the capture stream
  3938. hr = captureAudioClient->Reset();
  3939. if ( FAILED( hr ) ) {
  3940. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  3941. goto Exit;
  3942. }
  3943. // start the capture stream
  3944. hr = captureAudioClient->Start();
  3945. if ( FAILED( hr ) ) {
  3946. errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  3947. goto Exit;
  3948. }
  3949. }
  3950. // start render stream if applicable
  3951. if ( renderAudioClient ) {
  3952. hr = renderAudioClient->GetMixFormat( &renderFormat );
  3953. if ( FAILED( hr ) ) {
  3954. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  3955. goto Exit;
  3956. }
  3957. // initialize render stream according to desire buffer size
  3958. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) stream_.bufferSize * 10000000 / renderFormat->nSamplesPerSec );
  3959. if ( !renderClient ) {
  3960. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  3961. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  3962. desiredBufferPeriod,
  3963. desiredBufferPeriod,
  3964. renderFormat,
  3965. NULL );
  3966. if ( FAILED( hr ) ) {
  3967. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  3968. goto Exit;
  3969. }
  3970. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  3971. ( void** ) &renderClient );
  3972. if ( FAILED( hr ) ) {
  3973. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  3974. goto Exit;
  3975. }
  3976. // configure renderEvent to trigger on every available render buffer
  3977. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  3978. if ( !renderEvent ) {
  3979. errorType = RtAudioError::SYSTEM_ERROR;
  3980. errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";
  3981. goto Exit;
  3982. }
  3983. hr = renderAudioClient->SetEventHandle( renderEvent );
  3984. if ( FAILED( hr ) ) {
  3985. errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  3986. goto Exit;
  3987. }
  3988. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  3989. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  3990. }
  3991. unsigned int outBufferSize = 0;
  3992. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  3993. if ( FAILED( hr ) ) {
  3994. errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  3995. goto Exit;
  3996. }
  3997. // scale inBufferSize according to user->stream sample rate ratio
  3998. unsigned int inBufferSize = ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[OUTPUT];
  3999. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4000. // set renderBuffer size
  4001. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4002. // reset the render stream
  4003. hr = renderAudioClient->Reset();
  4004. if ( FAILED( hr ) ) {
  4005. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4006. goto Exit;
  4007. }
  4008. // start the render stream
  4009. hr = renderAudioClient->Start();
  4010. if ( FAILED( hr ) ) {
  4011. errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4012. goto Exit;
  4013. }
  4014. }
  4015. if ( stream_.mode == INPUT ) {
  4016. using namespace std; // for roundf
  4017. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4018. }
  4019. else if ( stream_.mode == OUTPUT ) {
  4020. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4021. }
  4022. else if ( stream_.mode == DUPLEX ) {
  4023. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4024. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4025. }
  4026. stream_.deviceBuffer = ( char* ) malloc( deviceBuffSize );
  4027. if ( !stream_.deviceBuffer ) {
  4028. errorType = RtAudioError::MEMORY_ERROR;
  4029. errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4030. goto Exit;
  4031. }
  4032. // stream process loop
  4033. while ( stream_.state != STREAM_STOPPING ) {
  4034. if ( !callbackPulled ) {
  4035. // Callback Input
  4036. // ==============
  4037. // 1. Pull callback buffer from inputBuffer
  4038. // 2. If 1. was successful: Convert callback buffer to user format
  4039. if ( captureAudioClient ) {
  4040. // Pull callback buffer from inputBuffer
  4041. callbackPulled = captureBuffer.pullBuffer( stream_.deviceBuffer,
  4042. ( unsigned int ) stream_.bufferSize * stream_.nDeviceChannels[INPUT],
  4043. stream_.deviceFormat[INPUT] );
  4044. if ( callbackPulled ) {
  4045. if ( stream_.doConvertBuffer[INPUT] ) {
  4046. // Convert callback buffer to user format
  4047. convertBuffer( stream_.userBuffer[INPUT],
  4048. stream_.deviceBuffer,
  4049. stream_.convertInfo[INPUT] );
  4050. }
  4051. else {
  4052. // no further conversion, simple copy deviceBuffer to userBuffer
  4053. memcpy( stream_.userBuffer[INPUT],
  4054. stream_.deviceBuffer,
  4055. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4056. }
  4057. }
  4058. }
  4059. else {
  4060. // if there is no capture stream, set callbackPulled flag
  4061. callbackPulled = true;
  4062. }
  4063. // Execute Callback
  4064. // ================
  4065. // 1. Execute user callback method
  4066. // 2. Handle return value from callback
  4067. // if callback has not requested the stream to stop
  4068. if ( callbackPulled && !callbackStopped ) {
  4069. // Execute user callback method
  4070. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4071. stream_.userBuffer[INPUT],
  4072. stream_.bufferSize,
  4073. getStreamTime(),
  4074. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4075. stream_.callbackInfo.userData );
  4076. // Handle return value from callback
  4077. if ( callbackResult == 1 ) {
  4078. // instantiate a thread to stop this thread
  4079. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4080. if ( !threadHandle ) {
  4081. errorType = RtAudioError::THREAD_ERROR;
  4082. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4083. goto Exit;
  4084. }
  4085. else if ( !CloseHandle( threadHandle ) ) {
  4086. errorType = RtAudioError::THREAD_ERROR;
  4087. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4088. goto Exit;
  4089. }
  4090. callbackStopped = true;
  4091. }
  4092. else if ( callbackResult == 2 ) {
  4093. // instantiate a thread to stop this thread
  4094. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4095. if ( !threadHandle ) {
  4096. errorType = RtAudioError::THREAD_ERROR;
  4097. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4098. goto Exit;
  4099. }
  4100. else if ( !CloseHandle( threadHandle ) ) {
  4101. errorType = RtAudioError::THREAD_ERROR;
  4102. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4103. goto Exit;
  4104. }
  4105. callbackStopped = true;
  4106. }
  4107. }
  4108. }
  4109. // Callback Output
  4110. // ===============
  4111. // 1. Convert callback buffer to stream format
  4112. // 2. Push callback buffer into outputBuffer
  4113. if ( renderAudioClient && callbackPulled ) {
  4114. if ( stream_.doConvertBuffer[OUTPUT] ) {
  4115. // Convert callback buffer to stream format
  4116. convertBuffer( stream_.deviceBuffer,
  4117. stream_.userBuffer[OUTPUT],
  4118. stream_.convertInfo[OUTPUT] );
  4119. }
  4120. // Push callback buffer into outputBuffer
  4121. callbackPushed = renderBuffer.pushBuffer( stream_.deviceBuffer,
  4122. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT],
  4123. stream_.deviceFormat[OUTPUT] );
  4124. }
  4125. else {
  4126. // if there is no render stream, set callbackPushed flag
  4127. callbackPushed = true;
  4128. }
  4129. // Stream Capture
  4130. // ==============
  4131. // 1. Get capture buffer from stream
  4132. // 2. Push capture buffer into inputBuffer
  4133. // 3. If 2. was successful: Release capture buffer
  4134. if ( captureAudioClient ) {
  4135. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4136. if ( !callbackPulled ) {
  4137. WaitForSingleObject( captureEvent, INFINITE );
  4138. }
  4139. // Get capture buffer from stream
  4140. hr = captureClient->GetBuffer( &streamBuffer,
  4141. &bufferFrameCount,
  4142. &captureFlags, NULL, NULL );
  4143. if ( FAILED( hr ) ) {
  4144. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4145. goto Exit;
  4146. }
  4147. if ( bufferFrameCount != 0 ) {
  4148. // Push capture buffer into inputBuffer
  4149. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4150. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4151. stream_.deviceFormat[INPUT] ) )
  4152. {
  4153. // Release capture buffer
  4154. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4155. if ( FAILED( hr ) ) {
  4156. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4157. goto Exit;
  4158. }
  4159. }
  4160. else
  4161. {
  4162. // Inform WASAPI that capture was unsuccessful
  4163. hr = captureClient->ReleaseBuffer( 0 );
  4164. if ( FAILED( hr ) ) {
  4165. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4166. goto Exit;
  4167. }
  4168. }
  4169. }
  4170. else
  4171. {
  4172. // Inform WASAPI that capture was unsuccessful
  4173. hr = captureClient->ReleaseBuffer( 0 );
  4174. if ( FAILED( hr ) ) {
  4175. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4176. goto Exit;
  4177. }
  4178. }
  4179. }
  4180. // Stream Render
  4181. // =============
  4182. // 1. Get render buffer from stream
  4183. // 2. Pull next buffer from outputBuffer
  4184. // 3. If 2. was successful: Fill render buffer with next buffer
  4185. // Release render buffer
  4186. if ( renderAudioClient ) {
  4187. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4188. if ( callbackPulled && !callbackPushed ) {
  4189. WaitForSingleObject( renderEvent, INFINITE );
  4190. }
  4191. // Get render buffer from stream
  4192. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4193. if ( FAILED( hr ) ) {
  4194. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4195. goto Exit;
  4196. }
  4197. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4198. if ( FAILED( hr ) ) {
  4199. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4200. goto Exit;
  4201. }
  4202. bufferFrameCount -= numFramesPadding;
  4203. if ( bufferFrameCount != 0 ) {
  4204. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4205. if ( FAILED( hr ) ) {
  4206. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4207. goto Exit;
  4208. }
  4209. // Pull next buffer from outputBuffer
  4210. // Fill render buffer with next buffer
  4211. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4212. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4213. stream_.deviceFormat[OUTPUT] ) )
  4214. {
  4215. // Release render buffer
  4216. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4217. if ( FAILED( hr ) ) {
  4218. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4219. goto Exit;
  4220. }
  4221. }
  4222. else
  4223. {
  4224. // Inform WASAPI that render was unsuccessful
  4225. hr = renderClient->ReleaseBuffer( 0, 0 );
  4226. if ( FAILED( hr ) ) {
  4227. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4228. goto Exit;
  4229. }
  4230. }
  4231. }
  4232. else
  4233. {
  4234. // Inform WASAPI that render was unsuccessful
  4235. hr = renderClient->ReleaseBuffer( 0, 0 );
  4236. if ( FAILED( hr ) ) {
  4237. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4238. goto Exit;
  4239. }
  4240. }
  4241. }
  4242. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4243. if ( callbackPushed ) {
  4244. callbackPulled = false;
  4245. // tick stream time
  4246. RtApi::tickStreamTime();
  4247. }
  4248. }
  4249. Exit:
  4250. // clean up
  4251. CoTaskMemFree( captureFormat );
  4252. CoTaskMemFree( renderFormat );
  4253. CoUninitialize();
  4254. // update stream state
  4255. stream_.state = STREAM_STOPPED;
  4256. if ( errorText_.empty() )
  4257. return;
  4258. else
  4259. error( errorType );
  4260. }
  4261. //******************** End of __WINDOWS_WASAPI__ *********************//
  4262. #endif
  4263. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4264. // Modified by Robin Davies, October 2005
  4265. // - Improvements to DirectX pointer chasing.
  4266. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4267. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4268. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4269. // Changed device query structure for RtAudio 4.0.7, January 2010
  4270. #include <mmsystem.h>
  4271. #include <mmreg.h>
  4272. #include <dsound.h>
  4273. #include <assert.h>
  4274. #include <algorithm>
  4275. #if defined(__MINGW32__)
  4276. // missing from latest mingw winapi
  4277. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4278. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4279. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4280. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4281. #endif
  4282. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4283. #ifdef _MSC_VER // if Microsoft Visual C++
  4284. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4285. #endif
  4286. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4287. {
  4288. if ( pointer > bufferSize ) pointer -= bufferSize;
  4289. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4290. if ( pointer < earlierPointer ) pointer += bufferSize;
  4291. return pointer >= earlierPointer && pointer < laterPointer;
  4292. }
  4293. // A structure to hold various information related to the DirectSound
  4294. // API implementation.
  4295. struct DsHandle {
  4296. unsigned int drainCounter; // Tracks callback counts when draining
  4297. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4298. void *id[2];
  4299. void *buffer[2];
  4300. bool xrun[2];
  4301. UINT bufferPointer[2];
  4302. DWORD dsBufferSize[2];
  4303. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4304. HANDLE condition;
  4305. DsHandle()
  4306. :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; }
  4307. };
  4308. // Declarations for utility functions, callbacks, and structures
  4309. // specific to the DirectSound implementation.
  4310. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4311. LPCTSTR description,
  4312. LPCTSTR module,
  4313. LPVOID lpContext );
  4314. static const char* getErrorString( int code );
  4315. static unsigned __stdcall callbackHandler( void *ptr );
  4316. struct DsDevice {
  4317. LPGUID id[2];
  4318. bool validId[2];
  4319. bool found;
  4320. std::string name;
  4321. DsDevice()
  4322. : found(false) { validId[0] = false; validId[1] = false; }
  4323. };
  4324. struct DsProbeData {
  4325. bool isInput;
  4326. std::vector<struct DsDevice>* dsDevices;
  4327. };
  4328. RtApiDs :: RtApiDs()
  4329. {
  4330. // Dsound will run both-threaded. If CoInitialize fails, then just
  4331. // accept whatever the mainline chose for a threading model.
  4332. coInitialized_ = false;
  4333. HRESULT hr = CoInitialize( NULL );
  4334. if ( !FAILED( hr ) ) coInitialized_ = true;
  4335. }
  4336. RtApiDs :: ~RtApiDs()
  4337. {
  4338. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4339. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4340. }
  4341. // The DirectSound default output is always the first device.
  4342. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4343. {
  4344. return 0;
  4345. }
  4346. // The DirectSound default input is always the first input device,
  4347. // which is the first capture device enumerated.
  4348. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4349. {
  4350. return 0;
  4351. }
  4352. unsigned int RtApiDs :: getDeviceCount( void )
  4353. {
  4354. // Set query flag for previously found devices to false, so that we
  4355. // can check for any devices that have disappeared.
  4356. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4357. dsDevices[i].found = false;
  4358. // Query DirectSound devices.
  4359. struct DsProbeData probeInfo;
  4360. probeInfo.isInput = false;
  4361. probeInfo.dsDevices = &dsDevices;
  4362. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4363. if ( FAILED( result ) ) {
  4364. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4365. errorText_ = errorStream_.str();
  4366. error( RtAudioError::WARNING );
  4367. }
  4368. // Query DirectSoundCapture devices.
  4369. probeInfo.isInput = true;
  4370. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4371. if ( FAILED( result ) ) {
  4372. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4373. errorText_ = errorStream_.str();
  4374. error( RtAudioError::WARNING );
  4375. }
  4376. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4377. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4378. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4379. else i++;
  4380. }
  4381. return static_cast<unsigned int>(dsDevices.size());
  4382. }
  4383. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4384. {
  4385. RtAudio::DeviceInfo info;
  4386. info.probed = false;
  4387. if ( dsDevices.size() == 0 ) {
  4388. // Force a query of all devices
  4389. getDeviceCount();
  4390. if ( dsDevices.size() == 0 ) {
  4391. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4392. error( RtAudioError::INVALID_USE );
  4393. return info;
  4394. }
  4395. }
  4396. if ( device >= dsDevices.size() ) {
  4397. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4398. error( RtAudioError::INVALID_USE );
  4399. return info;
  4400. }
  4401. HRESULT result;
  4402. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4403. LPDIRECTSOUND output;
  4404. DSCAPS outCaps;
  4405. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4406. if ( FAILED( result ) ) {
  4407. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4408. errorText_ = errorStream_.str();
  4409. error( RtAudioError::WARNING );
  4410. goto probeInput;
  4411. }
  4412. outCaps.dwSize = sizeof( outCaps );
  4413. result = output->GetCaps( &outCaps );
  4414. if ( FAILED( result ) ) {
  4415. output->Release();
  4416. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4417. errorText_ = errorStream_.str();
  4418. error( RtAudioError::WARNING );
  4419. goto probeInput;
  4420. }
  4421. // Get output channel information.
  4422. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4423. // Get sample rate information.
  4424. info.sampleRates.clear();
  4425. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4426. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4427. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4428. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4429. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4430. info.preferredSampleRate = SAMPLE_RATES[k];
  4431. }
  4432. }
  4433. // Get format information.
  4434. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4435. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4436. output->Release();
  4437. if ( getDefaultOutputDevice() == device )
  4438. info.isDefaultOutput = true;
  4439. if ( dsDevices[ device ].validId[1] == false ) {
  4440. info.name = dsDevices[ device ].name;
  4441. info.probed = true;
  4442. return info;
  4443. }
  4444. probeInput:
  4445. LPDIRECTSOUNDCAPTURE input;
  4446. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4447. if ( FAILED( result ) ) {
  4448. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4449. errorText_ = errorStream_.str();
  4450. error( RtAudioError::WARNING );
  4451. return info;
  4452. }
  4453. DSCCAPS inCaps;
  4454. inCaps.dwSize = sizeof( inCaps );
  4455. result = input->GetCaps( &inCaps );
  4456. if ( FAILED( result ) ) {
  4457. input->Release();
  4458. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4459. errorText_ = errorStream_.str();
  4460. error( RtAudioError::WARNING );
  4461. return info;
  4462. }
  4463. // Get input channel information.
  4464. info.inputChannels = inCaps.dwChannels;
  4465. // Get sample rate and format information.
  4466. std::vector<unsigned int> rates;
  4467. if ( inCaps.dwChannels >= 2 ) {
  4468. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4469. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4470. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4471. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4472. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4473. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4474. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4475. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4476. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4477. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4478. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4479. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4480. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4481. }
  4482. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4483. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4484. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4485. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4486. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4487. }
  4488. }
  4489. else if ( inCaps.dwChannels == 1 ) {
  4490. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4491. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4492. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4493. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4494. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4495. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4496. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4497. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4498. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4499. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4500. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4501. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4502. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4503. }
  4504. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4505. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4506. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4507. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4508. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4509. }
  4510. }
  4511. else info.inputChannels = 0; // technically, this would be an error
  4512. input->Release();
  4513. if ( info.inputChannels == 0 ) return info;
  4514. // Copy the supported rates to the info structure but avoid duplication.
  4515. bool found;
  4516. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4517. found = false;
  4518. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4519. if ( rates[i] == info.sampleRates[j] ) {
  4520. found = true;
  4521. break;
  4522. }
  4523. }
  4524. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4525. }
  4526. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4527. // If device opens for both playback and capture, we determine the channels.
  4528. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4529. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4530. if ( device == 0 ) info.isDefaultInput = true;
  4531. // Copy name and return.
  4532. info.name = dsDevices[ device ].name;
  4533. info.probed = true;
  4534. return info;
  4535. }
  4536. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4537. unsigned int firstChannel, unsigned int sampleRate,
  4538. RtAudioFormat format, unsigned int *bufferSize,
  4539. RtAudio::StreamOptions *options )
  4540. {
  4541. if ( channels + firstChannel > 2 ) {
  4542. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4543. return FAILURE;
  4544. }
  4545. size_t nDevices = dsDevices.size();
  4546. if ( nDevices == 0 ) {
  4547. // This should not happen because a check is made before this function is called.
  4548. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4549. return FAILURE;
  4550. }
  4551. if ( device >= nDevices ) {
  4552. // This should not happen because a check is made before this function is called.
  4553. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4554. return FAILURE;
  4555. }
  4556. if ( mode == OUTPUT ) {
  4557. if ( dsDevices[ device ].validId[0] == false ) {
  4558. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4559. errorText_ = errorStream_.str();
  4560. return FAILURE;
  4561. }
  4562. }
  4563. else { // mode == INPUT
  4564. if ( dsDevices[ device ].validId[1] == false ) {
  4565. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4566. errorText_ = errorStream_.str();
  4567. return FAILURE;
  4568. }
  4569. }
  4570. // According to a note in PortAudio, using GetDesktopWindow()
  4571. // instead of GetForegroundWindow() is supposed to avoid problems
  4572. // that occur when the application's window is not the foreground
  4573. // window. Also, if the application window closes before the
  4574. // DirectSound buffer, DirectSound can crash. In the past, I had
  4575. // problems when using GetDesktopWindow() but it seems fine now
  4576. // (January 2010). I'll leave it commented here.
  4577. // HWND hWnd = GetForegroundWindow();
  4578. HWND hWnd = GetDesktopWindow();
  4579. // Check the numberOfBuffers parameter and limit the lowest value to
  4580. // two. This is a judgement call and a value of two is probably too
  4581. // low for capture, but it should work for playback.
  4582. int nBuffers = 0;
  4583. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  4584. if ( options && options->numberOfBuffers > 0 ) nBuffers = options->numberOfBuffers;
  4585. if ( nBuffers < 2 ) nBuffers = 3;
  4586. // Check the lower range of the user-specified buffer size and set
  4587. // (arbitrarily) to a lower bound of 32.
  4588. if ( *bufferSize < 32 ) *bufferSize = 32;
  4589. // Create the wave format structure. The data format setting will
  4590. // be determined later.
  4591. WAVEFORMATEX waveFormat;
  4592. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  4593. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  4594. waveFormat.nChannels = channels + firstChannel;
  4595. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  4596. // Determine the device buffer size. By default, we'll use the value
  4597. // defined above (32K), but we will grow it to make allowances for
  4598. // very large software buffer sizes.
  4599. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  4600. DWORD dsPointerLeadTime = 0;
  4601. void *ohandle = 0, *bhandle = 0;
  4602. HRESULT result;
  4603. if ( mode == OUTPUT ) {
  4604. LPDIRECTSOUND output;
  4605. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4606. if ( FAILED( result ) ) {
  4607. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4608. errorText_ = errorStream_.str();
  4609. return FAILURE;
  4610. }
  4611. DSCAPS outCaps;
  4612. outCaps.dwSize = sizeof( outCaps );
  4613. result = output->GetCaps( &outCaps );
  4614. if ( FAILED( result ) ) {
  4615. output->Release();
  4616. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  4617. errorText_ = errorStream_.str();
  4618. return FAILURE;
  4619. }
  4620. // Check channel information.
  4621. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  4622. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  4623. errorText_ = errorStream_.str();
  4624. return FAILURE;
  4625. }
  4626. // Check format information. Use 16-bit format unless not
  4627. // supported or user requests 8-bit.
  4628. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  4629. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  4630. waveFormat.wBitsPerSample = 16;
  4631. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4632. }
  4633. else {
  4634. waveFormat.wBitsPerSample = 8;
  4635. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4636. }
  4637. stream_.userFormat = format;
  4638. // Update wave format structure and buffer information.
  4639. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4640. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4641. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4642. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4643. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4644. dsBufferSize *= 2;
  4645. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  4646. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  4647. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  4648. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  4649. if ( FAILED( result ) ) {
  4650. output->Release();
  4651. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  4652. errorText_ = errorStream_.str();
  4653. return FAILURE;
  4654. }
  4655. // Even though we will write to the secondary buffer, we need to
  4656. // access the primary buffer to set the correct output format
  4657. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  4658. // buffer description.
  4659. DSBUFFERDESC bufferDescription;
  4660. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4661. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4662. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  4663. // Obtain the primary buffer
  4664. LPDIRECTSOUNDBUFFER buffer;
  4665. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4666. if ( FAILED( result ) ) {
  4667. output->Release();
  4668. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  4669. errorText_ = errorStream_.str();
  4670. return FAILURE;
  4671. }
  4672. // Set the primary DS buffer sound format.
  4673. result = buffer->SetFormat( &waveFormat );
  4674. if ( FAILED( result ) ) {
  4675. output->Release();
  4676. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  4677. errorText_ = errorStream_.str();
  4678. return FAILURE;
  4679. }
  4680. // Setup the secondary DS buffer description.
  4681. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4682. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4683. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4684. DSBCAPS_GLOBALFOCUS |
  4685. DSBCAPS_GETCURRENTPOSITION2 |
  4686. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  4687. bufferDescription.dwBufferBytes = dsBufferSize;
  4688. bufferDescription.lpwfxFormat = &waveFormat;
  4689. // Try to create the secondary DS buffer. If that doesn't work,
  4690. // try to use software mixing. Otherwise, there's a problem.
  4691. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4692. if ( FAILED( result ) ) {
  4693. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4694. DSBCAPS_GLOBALFOCUS |
  4695. DSBCAPS_GETCURRENTPOSITION2 |
  4696. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  4697. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4698. if ( FAILED( result ) ) {
  4699. output->Release();
  4700. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  4701. errorText_ = errorStream_.str();
  4702. return FAILURE;
  4703. }
  4704. }
  4705. // Get the buffer size ... might be different from what we specified.
  4706. DSBCAPS dsbcaps;
  4707. dsbcaps.dwSize = sizeof( DSBCAPS );
  4708. result = buffer->GetCaps( &dsbcaps );
  4709. if ( FAILED( result ) ) {
  4710. output->Release();
  4711. buffer->Release();
  4712. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4713. errorText_ = errorStream_.str();
  4714. return FAILURE;
  4715. }
  4716. dsBufferSize = dsbcaps.dwBufferBytes;
  4717. // Lock the DS buffer
  4718. LPVOID audioPtr;
  4719. DWORD dataLen;
  4720. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4721. if ( FAILED( result ) ) {
  4722. output->Release();
  4723. buffer->Release();
  4724. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  4725. errorText_ = errorStream_.str();
  4726. return FAILURE;
  4727. }
  4728. // Zero the DS buffer
  4729. ZeroMemory( audioPtr, dataLen );
  4730. // Unlock the DS buffer
  4731. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4732. if ( FAILED( result ) ) {
  4733. output->Release();
  4734. buffer->Release();
  4735. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  4736. errorText_ = errorStream_.str();
  4737. return FAILURE;
  4738. }
  4739. ohandle = (void *) output;
  4740. bhandle = (void *) buffer;
  4741. }
  4742. if ( mode == INPUT ) {
  4743. LPDIRECTSOUNDCAPTURE input;
  4744. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4745. if ( FAILED( result ) ) {
  4746. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4747. errorText_ = errorStream_.str();
  4748. return FAILURE;
  4749. }
  4750. DSCCAPS inCaps;
  4751. inCaps.dwSize = sizeof( inCaps );
  4752. result = input->GetCaps( &inCaps );
  4753. if ( FAILED( result ) ) {
  4754. input->Release();
  4755. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  4756. errorText_ = errorStream_.str();
  4757. return FAILURE;
  4758. }
  4759. // Check channel information.
  4760. if ( inCaps.dwChannels < channels + firstChannel ) {
  4761. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  4762. return FAILURE;
  4763. }
  4764. // Check format information. Use 16-bit format unless user
  4765. // requests 8-bit.
  4766. DWORD deviceFormats;
  4767. if ( channels + firstChannel == 2 ) {
  4768. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  4769. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4770. waveFormat.wBitsPerSample = 8;
  4771. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4772. }
  4773. else { // assume 16-bit is supported
  4774. waveFormat.wBitsPerSample = 16;
  4775. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4776. }
  4777. }
  4778. else { // channel == 1
  4779. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  4780. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4781. waveFormat.wBitsPerSample = 8;
  4782. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4783. }
  4784. else { // assume 16-bit is supported
  4785. waveFormat.wBitsPerSample = 16;
  4786. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4787. }
  4788. }
  4789. stream_.userFormat = format;
  4790. // Update wave format structure and buffer information.
  4791. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4792. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4793. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4794. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4795. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4796. dsBufferSize *= 2;
  4797. // Setup the secondary DS buffer description.
  4798. DSCBUFFERDESC bufferDescription;
  4799. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  4800. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  4801. bufferDescription.dwFlags = 0;
  4802. bufferDescription.dwReserved = 0;
  4803. bufferDescription.dwBufferBytes = dsBufferSize;
  4804. bufferDescription.lpwfxFormat = &waveFormat;
  4805. // Create the capture buffer.
  4806. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  4807. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  4808. if ( FAILED( result ) ) {
  4809. input->Release();
  4810. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  4811. errorText_ = errorStream_.str();
  4812. return FAILURE;
  4813. }
  4814. // Get the buffer size ... might be different from what we specified.
  4815. DSCBCAPS dscbcaps;
  4816. dscbcaps.dwSize = sizeof( DSCBCAPS );
  4817. result = buffer->GetCaps( &dscbcaps );
  4818. if ( FAILED( result ) ) {
  4819. input->Release();
  4820. buffer->Release();
  4821. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4822. errorText_ = errorStream_.str();
  4823. return FAILURE;
  4824. }
  4825. dsBufferSize = dscbcaps.dwBufferBytes;
  4826. // NOTE: We could have a problem here if this is a duplex stream
  4827. // and the play and capture hardware buffer sizes are different
  4828. // (I'm actually not sure if that is a problem or not).
  4829. // Currently, we are not verifying that.
  4830. // Lock the capture buffer
  4831. LPVOID audioPtr;
  4832. DWORD dataLen;
  4833. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4834. if ( FAILED( result ) ) {
  4835. input->Release();
  4836. buffer->Release();
  4837. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  4838. errorText_ = errorStream_.str();
  4839. return FAILURE;
  4840. }
  4841. // Zero the buffer
  4842. ZeroMemory( audioPtr, dataLen );
  4843. // Unlock the buffer
  4844. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4845. if ( FAILED( result ) ) {
  4846. input->Release();
  4847. buffer->Release();
  4848. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  4849. errorText_ = errorStream_.str();
  4850. return FAILURE;
  4851. }
  4852. ohandle = (void *) input;
  4853. bhandle = (void *) buffer;
  4854. }
  4855. // Set various stream parameters
  4856. DsHandle *handle = 0;
  4857. stream_.nDeviceChannels[mode] = channels + firstChannel;
  4858. stream_.nUserChannels[mode] = channels;
  4859. stream_.bufferSize = *bufferSize;
  4860. stream_.channelOffset[mode] = firstChannel;
  4861. stream_.deviceInterleaved[mode] = true;
  4862. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  4863. else stream_.userInterleaved = true;
  4864. // Set flag for buffer conversion
  4865. stream_.doConvertBuffer[mode] = false;
  4866. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  4867. stream_.doConvertBuffer[mode] = true;
  4868. if (stream_.userFormat != stream_.deviceFormat[mode])
  4869. stream_.doConvertBuffer[mode] = true;
  4870. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4871. stream_.nUserChannels[mode] > 1 )
  4872. stream_.doConvertBuffer[mode] = true;
  4873. // Allocate necessary internal buffers
  4874. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  4875. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  4876. if ( stream_.userBuffer[mode] == NULL ) {
  4877. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  4878. goto error;
  4879. }
  4880. if ( stream_.doConvertBuffer[mode] ) {
  4881. bool makeBuffer = true;
  4882. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  4883. if ( mode == INPUT ) {
  4884. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  4885. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  4886. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  4887. }
  4888. }
  4889. if ( makeBuffer ) {
  4890. bufferBytes *= *bufferSize;
  4891. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  4892. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  4893. if ( stream_.deviceBuffer == NULL ) {
  4894. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  4895. goto error;
  4896. }
  4897. }
  4898. }
  4899. // Allocate our DsHandle structures for the stream.
  4900. if ( stream_.apiHandle == 0 ) {
  4901. try {
  4902. handle = new DsHandle;
  4903. }
  4904. catch ( std::bad_alloc& ) {
  4905. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  4906. goto error;
  4907. }
  4908. // Create a manual-reset event.
  4909. handle->condition = CreateEvent( NULL, // no security
  4910. TRUE, // manual-reset
  4911. FALSE, // non-signaled initially
  4912. NULL ); // unnamed
  4913. stream_.apiHandle = (void *) handle;
  4914. }
  4915. else
  4916. handle = (DsHandle *) stream_.apiHandle;
  4917. handle->id[mode] = ohandle;
  4918. handle->buffer[mode] = bhandle;
  4919. handle->dsBufferSize[mode] = dsBufferSize;
  4920. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  4921. stream_.device[mode] = device;
  4922. stream_.state = STREAM_STOPPED;
  4923. if ( stream_.mode == OUTPUT && mode == INPUT )
  4924. // We had already set up an output stream.
  4925. stream_.mode = DUPLEX;
  4926. else
  4927. stream_.mode = mode;
  4928. stream_.nBuffers = nBuffers;
  4929. stream_.sampleRate = sampleRate;
  4930. // Setup the buffer conversion information structure.
  4931. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  4932. // Setup the callback thread.
  4933. if ( stream_.callbackInfo.isRunning == false ) {
  4934. unsigned threadId;
  4935. stream_.callbackInfo.isRunning = true;
  4936. stream_.callbackInfo.object = (void *) this;
  4937. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  4938. &stream_.callbackInfo, 0, &threadId );
  4939. if ( stream_.callbackInfo.thread == 0 ) {
  4940. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  4941. goto error;
  4942. }
  4943. // Boost DS thread priority
  4944. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  4945. }
  4946. return SUCCESS;
  4947. error:
  4948. if ( handle ) {
  4949. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  4950. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  4951. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  4952. if ( buffer ) buffer->Release();
  4953. object->Release();
  4954. }
  4955. if ( handle->buffer[1] ) {
  4956. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  4957. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  4958. if ( buffer ) buffer->Release();
  4959. object->Release();
  4960. }
  4961. CloseHandle( handle->condition );
  4962. delete handle;
  4963. stream_.apiHandle = 0;
  4964. }
  4965. for ( int i=0; i<2; i++ ) {
  4966. if ( stream_.userBuffer[i] ) {
  4967. free( stream_.userBuffer[i] );
  4968. stream_.userBuffer[i] = 0;
  4969. }
  4970. }
  4971. if ( stream_.deviceBuffer ) {
  4972. free( stream_.deviceBuffer );
  4973. stream_.deviceBuffer = 0;
  4974. }
  4975. stream_.state = STREAM_CLOSED;
  4976. return FAILURE;
  4977. }
  4978. void RtApiDs :: closeStream()
  4979. {
  4980. if ( stream_.state == STREAM_CLOSED ) {
  4981. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  4982. error( RtAudioError::WARNING );
  4983. return;
  4984. }
  4985. // Stop the callback thread.
  4986. stream_.callbackInfo.isRunning = false;
  4987. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  4988. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  4989. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  4990. if ( handle ) {
  4991. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  4992. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  4993. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  4994. if ( buffer ) {
  4995. buffer->Stop();
  4996. buffer->Release();
  4997. }
  4998. object->Release();
  4999. }
  5000. if ( handle->buffer[1] ) {
  5001. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5002. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5003. if ( buffer ) {
  5004. buffer->Stop();
  5005. buffer->Release();
  5006. }
  5007. object->Release();
  5008. }
  5009. CloseHandle( handle->condition );
  5010. delete handle;
  5011. stream_.apiHandle = 0;
  5012. }
  5013. for ( int i=0; i<2; i++ ) {
  5014. if ( stream_.userBuffer[i] ) {
  5015. free( stream_.userBuffer[i] );
  5016. stream_.userBuffer[i] = 0;
  5017. }
  5018. }
  5019. if ( stream_.deviceBuffer ) {
  5020. free( stream_.deviceBuffer );
  5021. stream_.deviceBuffer = 0;
  5022. }
  5023. stream_.mode = UNINITIALIZED;
  5024. stream_.state = STREAM_CLOSED;
  5025. }
  5026. void RtApiDs :: startStream()
  5027. {
  5028. verifyStream();
  5029. if ( stream_.state == STREAM_RUNNING ) {
  5030. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5031. error( RtAudioError::WARNING );
  5032. return;
  5033. }
  5034. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5035. // Increase scheduler frequency on lesser windows (a side-effect of
  5036. // increasing timer accuracy). On greater windows (Win2K or later),
  5037. // this is already in effect.
  5038. timeBeginPeriod( 1 );
  5039. buffersRolling = false;
  5040. duplexPrerollBytes = 0;
  5041. if ( stream_.mode == DUPLEX ) {
  5042. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5043. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5044. }
  5045. HRESULT result = 0;
  5046. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5047. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5048. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5049. if ( FAILED( result ) ) {
  5050. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5051. errorText_ = errorStream_.str();
  5052. goto unlock;
  5053. }
  5054. }
  5055. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5056. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5057. result = buffer->Start( DSCBSTART_LOOPING );
  5058. if ( FAILED( result ) ) {
  5059. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5060. errorText_ = errorStream_.str();
  5061. goto unlock;
  5062. }
  5063. }
  5064. handle->drainCounter = 0;
  5065. handle->internalDrain = false;
  5066. ResetEvent( handle->condition );
  5067. stream_.state = STREAM_RUNNING;
  5068. unlock:
  5069. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5070. }
  5071. void RtApiDs :: stopStream()
  5072. {
  5073. verifyStream();
  5074. if ( stream_.state == STREAM_STOPPED ) {
  5075. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5076. error( RtAudioError::WARNING );
  5077. return;
  5078. }
  5079. HRESULT result = 0;
  5080. LPVOID audioPtr;
  5081. DWORD dataLen;
  5082. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5083. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5084. if ( handle->drainCounter == 0 ) {
  5085. handle->drainCounter = 2;
  5086. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5087. }
  5088. stream_.state = STREAM_STOPPED;
  5089. MUTEX_LOCK( &stream_.mutex );
  5090. // Stop the buffer and clear memory
  5091. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5092. result = buffer->Stop();
  5093. if ( FAILED( result ) ) {
  5094. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5095. errorText_ = errorStream_.str();
  5096. goto unlock;
  5097. }
  5098. // Lock the buffer and clear it so that if we start to play again,
  5099. // we won't have old data playing.
  5100. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5101. if ( FAILED( result ) ) {
  5102. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5103. errorText_ = errorStream_.str();
  5104. goto unlock;
  5105. }
  5106. // Zero the DS buffer
  5107. ZeroMemory( audioPtr, dataLen );
  5108. // Unlock the DS buffer
  5109. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5110. if ( FAILED( result ) ) {
  5111. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5112. errorText_ = errorStream_.str();
  5113. goto unlock;
  5114. }
  5115. // If we start playing again, we must begin at beginning of buffer.
  5116. handle->bufferPointer[0] = 0;
  5117. }
  5118. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5119. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5120. audioPtr = NULL;
  5121. dataLen = 0;
  5122. stream_.state = STREAM_STOPPED;
  5123. if ( stream_.mode != DUPLEX )
  5124. MUTEX_LOCK( &stream_.mutex );
  5125. result = buffer->Stop();
  5126. if ( FAILED( result ) ) {
  5127. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5128. errorText_ = errorStream_.str();
  5129. goto unlock;
  5130. }
  5131. // Lock the buffer and clear it so that if we start to play again,
  5132. // we won't have old data playing.
  5133. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5134. if ( FAILED( result ) ) {
  5135. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5136. errorText_ = errorStream_.str();
  5137. goto unlock;
  5138. }
  5139. // Zero the DS buffer
  5140. ZeroMemory( audioPtr, dataLen );
  5141. // Unlock the DS buffer
  5142. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5143. if ( FAILED( result ) ) {
  5144. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5145. errorText_ = errorStream_.str();
  5146. goto unlock;
  5147. }
  5148. // If we start recording again, we must begin at beginning of buffer.
  5149. handle->bufferPointer[1] = 0;
  5150. }
  5151. unlock:
  5152. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5153. MUTEX_UNLOCK( &stream_.mutex );
  5154. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5155. }
  5156. void RtApiDs :: abortStream()
  5157. {
  5158. verifyStream();
  5159. if ( stream_.state == STREAM_STOPPED ) {
  5160. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5161. error( RtAudioError::WARNING );
  5162. return;
  5163. }
  5164. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5165. handle->drainCounter = 2;
  5166. stopStream();
  5167. }
  5168. void RtApiDs :: callbackEvent()
  5169. {
  5170. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5171. Sleep( 50 ); // sleep 50 milliseconds
  5172. return;
  5173. }
  5174. if ( stream_.state == STREAM_CLOSED ) {
  5175. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5176. error( RtAudioError::WARNING );
  5177. return;
  5178. }
  5179. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5180. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5181. // Check if we were draining the stream and signal is finished.
  5182. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5183. stream_.state = STREAM_STOPPING;
  5184. if ( handle->internalDrain == false )
  5185. SetEvent( handle->condition );
  5186. else
  5187. stopStream();
  5188. return;
  5189. }
  5190. // Invoke user callback to get fresh output data UNLESS we are
  5191. // draining stream.
  5192. if ( handle->drainCounter == 0 ) {
  5193. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5194. double streamTime = getStreamTime();
  5195. RtAudioStreamStatus status = 0;
  5196. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5197. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5198. handle->xrun[0] = false;
  5199. }
  5200. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5201. status |= RTAUDIO_INPUT_OVERFLOW;
  5202. handle->xrun[1] = false;
  5203. }
  5204. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5205. stream_.bufferSize, streamTime, status, info->userData );
  5206. if ( cbReturnValue == 2 ) {
  5207. stream_.state = STREAM_STOPPING;
  5208. handle->drainCounter = 2;
  5209. abortStream();
  5210. return;
  5211. }
  5212. else if ( cbReturnValue == 1 ) {
  5213. handle->drainCounter = 1;
  5214. handle->internalDrain = true;
  5215. }
  5216. }
  5217. HRESULT result;
  5218. DWORD currentWritePointer, safeWritePointer;
  5219. DWORD currentReadPointer, safeReadPointer;
  5220. UINT nextWritePointer;
  5221. LPVOID buffer1 = NULL;
  5222. LPVOID buffer2 = NULL;
  5223. DWORD bufferSize1 = 0;
  5224. DWORD bufferSize2 = 0;
  5225. char *buffer;
  5226. long bufferBytes;
  5227. MUTEX_LOCK( &stream_.mutex );
  5228. if ( stream_.state == STREAM_STOPPED ) {
  5229. MUTEX_UNLOCK( &stream_.mutex );
  5230. return;
  5231. }
  5232. if ( buffersRolling == false ) {
  5233. if ( stream_.mode == DUPLEX ) {
  5234. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5235. // It takes a while for the devices to get rolling. As a result,
  5236. // there's no guarantee that the capture and write device pointers
  5237. // will move in lockstep. Wait here for both devices to start
  5238. // rolling, and then set our buffer pointers accordingly.
  5239. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5240. // bytes later than the write buffer.
  5241. // Stub: a serious risk of having a pre-emptive scheduling round
  5242. // take place between the two GetCurrentPosition calls... but I'm
  5243. // really not sure how to solve the problem. Temporarily boost to
  5244. // Realtime priority, maybe; but I'm not sure what priority the
  5245. // DirectSound service threads run at. We *should* be roughly
  5246. // within a ms or so of correct.
  5247. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5248. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5249. DWORD startSafeWritePointer, startSafeReadPointer;
  5250. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5251. if ( FAILED( result ) ) {
  5252. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5253. errorText_ = errorStream_.str();
  5254. MUTEX_UNLOCK( &stream_.mutex );
  5255. error( RtAudioError::SYSTEM_ERROR );
  5256. return;
  5257. }
  5258. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5259. if ( FAILED( result ) ) {
  5260. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5261. errorText_ = errorStream_.str();
  5262. MUTEX_UNLOCK( &stream_.mutex );
  5263. error( RtAudioError::SYSTEM_ERROR );
  5264. return;
  5265. }
  5266. while ( true ) {
  5267. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5268. if ( FAILED( result ) ) {
  5269. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5270. errorText_ = errorStream_.str();
  5271. MUTEX_UNLOCK( &stream_.mutex );
  5272. error( RtAudioError::SYSTEM_ERROR );
  5273. return;
  5274. }
  5275. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5276. if ( FAILED( result ) ) {
  5277. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5278. errorText_ = errorStream_.str();
  5279. MUTEX_UNLOCK( &stream_.mutex );
  5280. error( RtAudioError::SYSTEM_ERROR );
  5281. return;
  5282. }
  5283. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5284. Sleep( 1 );
  5285. }
  5286. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5287. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5288. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5289. handle->bufferPointer[1] = safeReadPointer;
  5290. }
  5291. else if ( stream_.mode == OUTPUT ) {
  5292. // Set the proper nextWritePosition after initial startup.
  5293. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5294. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5295. if ( FAILED( result ) ) {
  5296. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5297. errorText_ = errorStream_.str();
  5298. MUTEX_UNLOCK( &stream_.mutex );
  5299. error( RtAudioError::SYSTEM_ERROR );
  5300. return;
  5301. }
  5302. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5303. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5304. }
  5305. buffersRolling = true;
  5306. }
  5307. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5308. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5309. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5310. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5311. bufferBytes *= formatBytes( stream_.userFormat );
  5312. memset( stream_.userBuffer[0], 0, bufferBytes );
  5313. }
  5314. // Setup parameters and do buffer conversion if necessary.
  5315. if ( stream_.doConvertBuffer[0] ) {
  5316. buffer = stream_.deviceBuffer;
  5317. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5318. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5319. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5320. }
  5321. else {
  5322. buffer = stream_.userBuffer[0];
  5323. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5324. bufferBytes *= formatBytes( stream_.userFormat );
  5325. }
  5326. // No byte swapping necessary in DirectSound implementation.
  5327. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5328. // unsigned. So, we need to convert our signed 8-bit data here to
  5329. // unsigned.
  5330. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5331. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5332. DWORD dsBufferSize = handle->dsBufferSize[0];
  5333. nextWritePointer = handle->bufferPointer[0];
  5334. DWORD endWrite, leadPointer;
  5335. while ( true ) {
  5336. // Find out where the read and "safe write" pointers are.
  5337. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5338. if ( FAILED( result ) ) {
  5339. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5340. errorText_ = errorStream_.str();
  5341. MUTEX_UNLOCK( &stream_.mutex );
  5342. error( RtAudioError::SYSTEM_ERROR );
  5343. return;
  5344. }
  5345. // We will copy our output buffer into the region between
  5346. // safeWritePointer and leadPointer. If leadPointer is not
  5347. // beyond the next endWrite position, wait until it is.
  5348. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5349. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5350. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5351. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5352. endWrite = nextWritePointer + bufferBytes;
  5353. // Check whether the entire write region is behind the play pointer.
  5354. if ( leadPointer >= endWrite ) break;
  5355. // If we are here, then we must wait until the leadPointer advances
  5356. // beyond the end of our next write region. We use the
  5357. // Sleep() function to suspend operation until that happens.
  5358. double millis = ( endWrite - leadPointer ) * 1000.0;
  5359. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5360. if ( millis < 1.0 ) millis = 1.0;
  5361. Sleep( (DWORD) millis );
  5362. }
  5363. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5364. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5365. // We've strayed into the forbidden zone ... resync the read pointer.
  5366. handle->xrun[0] = true;
  5367. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5368. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5369. handle->bufferPointer[0] = nextWritePointer;
  5370. endWrite = nextWritePointer + bufferBytes;
  5371. }
  5372. // Lock free space in the buffer
  5373. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5374. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5375. if ( FAILED( result ) ) {
  5376. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5377. errorText_ = errorStream_.str();
  5378. MUTEX_UNLOCK( &stream_.mutex );
  5379. error( RtAudioError::SYSTEM_ERROR );
  5380. return;
  5381. }
  5382. // Copy our buffer into the DS buffer
  5383. CopyMemory( buffer1, buffer, bufferSize1 );
  5384. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5385. // Update our buffer offset and unlock sound buffer
  5386. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5387. if ( FAILED( result ) ) {
  5388. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5389. errorText_ = errorStream_.str();
  5390. MUTEX_UNLOCK( &stream_.mutex );
  5391. error( RtAudioError::SYSTEM_ERROR );
  5392. return;
  5393. }
  5394. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5395. handle->bufferPointer[0] = nextWritePointer;
  5396. }
  5397. // Don't bother draining input
  5398. if ( handle->drainCounter ) {
  5399. handle->drainCounter++;
  5400. goto unlock;
  5401. }
  5402. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5403. // Setup parameters.
  5404. if ( stream_.doConvertBuffer[1] ) {
  5405. buffer = stream_.deviceBuffer;
  5406. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5407. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5408. }
  5409. else {
  5410. buffer = stream_.userBuffer[1];
  5411. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5412. bufferBytes *= formatBytes( stream_.userFormat );
  5413. }
  5414. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5415. long nextReadPointer = handle->bufferPointer[1];
  5416. DWORD dsBufferSize = handle->dsBufferSize[1];
  5417. // Find out where the write and "safe read" pointers are.
  5418. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5419. if ( FAILED( result ) ) {
  5420. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5421. errorText_ = errorStream_.str();
  5422. MUTEX_UNLOCK( &stream_.mutex );
  5423. error( RtAudioError::SYSTEM_ERROR );
  5424. return;
  5425. }
  5426. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5427. DWORD endRead = nextReadPointer + bufferBytes;
  5428. // Handling depends on whether we are INPUT or DUPLEX.
  5429. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5430. // then a wait here will drag the write pointers into the forbidden zone.
  5431. //
  5432. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5433. // it's in a safe position. This causes dropouts, but it seems to be the only
  5434. // practical way to sync up the read and write pointers reliably, given the
  5435. // the very complex relationship between phase and increment of the read and write
  5436. // pointers.
  5437. //
  5438. // In order to minimize audible dropouts in DUPLEX mode, we will
  5439. // provide a pre-roll period of 0.5 seconds in which we return
  5440. // zeros from the read buffer while the pointers sync up.
  5441. if ( stream_.mode == DUPLEX ) {
  5442. if ( safeReadPointer < endRead ) {
  5443. if ( duplexPrerollBytes <= 0 ) {
  5444. // Pre-roll time over. Be more agressive.
  5445. int adjustment = endRead-safeReadPointer;
  5446. handle->xrun[1] = true;
  5447. // Two cases:
  5448. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5449. // and perform fine adjustments later.
  5450. // - small adjustments: back off by twice as much.
  5451. if ( adjustment >= 2*bufferBytes )
  5452. nextReadPointer = safeReadPointer-2*bufferBytes;
  5453. else
  5454. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5455. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5456. }
  5457. else {
  5458. // In pre=roll time. Just do it.
  5459. nextReadPointer = safeReadPointer - bufferBytes;
  5460. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5461. }
  5462. endRead = nextReadPointer + bufferBytes;
  5463. }
  5464. }
  5465. else { // mode == INPUT
  5466. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5467. // See comments for playback.
  5468. double millis = (endRead - safeReadPointer) * 1000.0;
  5469. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5470. if ( millis < 1.0 ) millis = 1.0;
  5471. Sleep( (DWORD) millis );
  5472. // Wake up and find out where we are now.
  5473. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5474. if ( FAILED( result ) ) {
  5475. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5476. errorText_ = errorStream_.str();
  5477. MUTEX_UNLOCK( &stream_.mutex );
  5478. error( RtAudioError::SYSTEM_ERROR );
  5479. return;
  5480. }
  5481. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5482. }
  5483. }
  5484. // Lock free space in the buffer
  5485. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5486. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5487. if ( FAILED( result ) ) {
  5488. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5489. errorText_ = errorStream_.str();
  5490. MUTEX_UNLOCK( &stream_.mutex );
  5491. error( RtAudioError::SYSTEM_ERROR );
  5492. return;
  5493. }
  5494. if ( duplexPrerollBytes <= 0 ) {
  5495. // Copy our buffer into the DS buffer
  5496. CopyMemory( buffer, buffer1, bufferSize1 );
  5497. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5498. }
  5499. else {
  5500. memset( buffer, 0, bufferSize1 );
  5501. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5502. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5503. }
  5504. // Update our buffer offset and unlock sound buffer
  5505. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5506. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5507. if ( FAILED( result ) ) {
  5508. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5509. errorText_ = errorStream_.str();
  5510. MUTEX_UNLOCK( &stream_.mutex );
  5511. error( RtAudioError::SYSTEM_ERROR );
  5512. return;
  5513. }
  5514. handle->bufferPointer[1] = nextReadPointer;
  5515. // No byte swapping necessary in DirectSound implementation.
  5516. // If necessary, convert 8-bit data from unsigned to signed.
  5517. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5518. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5519. // Do buffer conversion if necessary.
  5520. if ( stream_.doConvertBuffer[1] )
  5521. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5522. }
  5523. unlock:
  5524. MUTEX_UNLOCK( &stream_.mutex );
  5525. RtApi::tickStreamTime();
  5526. }
  5527. // Definitions for utility functions and callbacks
  5528. // specific to the DirectSound implementation.
  5529. static unsigned __stdcall callbackHandler( void *ptr )
  5530. {
  5531. CallbackInfo *info = (CallbackInfo *) ptr;
  5532. RtApiDs *object = (RtApiDs *) info->object;
  5533. bool* isRunning = &info->isRunning;
  5534. while ( *isRunning == true ) {
  5535. object->callbackEvent();
  5536. }
  5537. _endthreadex( 0 );
  5538. return 0;
  5539. }
  5540. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5541. LPCTSTR description,
  5542. LPCTSTR /*module*/,
  5543. LPVOID lpContext )
  5544. {
  5545. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5546. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5547. HRESULT hr;
  5548. bool validDevice = false;
  5549. if ( probeInfo.isInput == true ) {
  5550. DSCCAPS caps;
  5551. LPDIRECTSOUNDCAPTURE object;
  5552. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5553. if ( hr != DS_OK ) return TRUE;
  5554. caps.dwSize = sizeof(caps);
  5555. hr = object->GetCaps( &caps );
  5556. if ( hr == DS_OK ) {
  5557. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5558. validDevice = true;
  5559. }
  5560. object->Release();
  5561. }
  5562. else {
  5563. DSCAPS caps;
  5564. LPDIRECTSOUND object;
  5565. hr = DirectSoundCreate( lpguid, &object, NULL );
  5566. if ( hr != DS_OK ) return TRUE;
  5567. caps.dwSize = sizeof(caps);
  5568. hr = object->GetCaps( &caps );
  5569. if ( hr == DS_OK ) {
  5570. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  5571. validDevice = true;
  5572. }
  5573. object->Release();
  5574. }
  5575. // If good device, then save its name and guid.
  5576. std::string name = convertCharPointerToStdString( description );
  5577. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  5578. if ( lpguid == NULL )
  5579. name = "Default Device";
  5580. if ( validDevice ) {
  5581. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  5582. if ( dsDevices[i].name == name ) {
  5583. dsDevices[i].found = true;
  5584. if ( probeInfo.isInput ) {
  5585. dsDevices[i].id[1] = lpguid;
  5586. dsDevices[i].validId[1] = true;
  5587. }
  5588. else {
  5589. dsDevices[i].id[0] = lpguid;
  5590. dsDevices[i].validId[0] = true;
  5591. }
  5592. return TRUE;
  5593. }
  5594. }
  5595. DsDevice device;
  5596. device.name = name;
  5597. device.found = true;
  5598. if ( probeInfo.isInput ) {
  5599. device.id[1] = lpguid;
  5600. device.validId[1] = true;
  5601. }
  5602. else {
  5603. device.id[0] = lpguid;
  5604. device.validId[0] = true;
  5605. }
  5606. dsDevices.push_back( device );
  5607. }
  5608. return TRUE;
  5609. }
  5610. static const char* getErrorString( int code )
  5611. {
  5612. switch ( code ) {
  5613. case DSERR_ALLOCATED:
  5614. return "Already allocated";
  5615. case DSERR_CONTROLUNAVAIL:
  5616. return "Control unavailable";
  5617. case DSERR_INVALIDPARAM:
  5618. return "Invalid parameter";
  5619. case DSERR_INVALIDCALL:
  5620. return "Invalid call";
  5621. case DSERR_GENERIC:
  5622. return "Generic error";
  5623. case DSERR_PRIOLEVELNEEDED:
  5624. return "Priority level needed";
  5625. case DSERR_OUTOFMEMORY:
  5626. return "Out of memory";
  5627. case DSERR_BADFORMAT:
  5628. return "The sample rate or the channel format is not supported";
  5629. case DSERR_UNSUPPORTED:
  5630. return "Not supported";
  5631. case DSERR_NODRIVER:
  5632. return "No driver";
  5633. case DSERR_ALREADYINITIALIZED:
  5634. return "Already initialized";
  5635. case DSERR_NOAGGREGATION:
  5636. return "No aggregation";
  5637. case DSERR_BUFFERLOST:
  5638. return "Buffer lost";
  5639. case DSERR_OTHERAPPHASPRIO:
  5640. return "Another application already has priority";
  5641. case DSERR_UNINITIALIZED:
  5642. return "Uninitialized";
  5643. default:
  5644. return "DirectSound unknown error";
  5645. }
  5646. }
  5647. //******************** End of __WINDOWS_DS__ *********************//
  5648. #endif
  5649. #if defined(__LINUX_ALSA__)
  5650. #include <alsa/asoundlib.h>
  5651. #include <unistd.h>
  5652. // A structure to hold various information related to the ALSA API
  5653. // implementation.
  5654. struct AlsaHandle {
  5655. snd_pcm_t *handles[2];
  5656. bool synchronized;
  5657. bool xrun[2];
  5658. pthread_cond_t runnable_cv;
  5659. bool runnable;
  5660. AlsaHandle()
  5661. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  5662. };
  5663. static void *alsaCallbackHandler( void * ptr );
  5664. RtApiAlsa :: RtApiAlsa()
  5665. {
  5666. // Nothing to do here.
  5667. }
  5668. RtApiAlsa :: ~RtApiAlsa()
  5669. {
  5670. if ( stream_.state != STREAM_CLOSED ) closeStream();
  5671. }
  5672. unsigned int RtApiAlsa :: getDeviceCount( void )
  5673. {
  5674. unsigned nDevices = 0;
  5675. int result, subdevice, card;
  5676. char name[64];
  5677. snd_ctl_t *handle;
  5678. // Count cards and devices
  5679. card = -1;
  5680. snd_card_next( &card );
  5681. while ( card >= 0 ) {
  5682. sprintf( name, "hw:%d", card );
  5683. result = snd_ctl_open( &handle, name, 0 );
  5684. if ( result < 0 ) {
  5685. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5686. errorText_ = errorStream_.str();
  5687. error( RtAudioError::WARNING );
  5688. goto nextcard;
  5689. }
  5690. subdevice = -1;
  5691. while( 1 ) {
  5692. result = snd_ctl_pcm_next_device( handle, &subdevice );
  5693. if ( result < 0 ) {
  5694. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5695. errorText_ = errorStream_.str();
  5696. error( RtAudioError::WARNING );
  5697. break;
  5698. }
  5699. if ( subdevice < 0 )
  5700. break;
  5701. nDevices++;
  5702. }
  5703. nextcard:
  5704. if (result == 0) {
  5705. snd_ctl_close( handle );
  5706. }
  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