RtAudio.cpp 351 KB

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