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

RtAudio.cpp 357KB

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