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 299KB

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